基于多个等式在元组列表上设置减法的最快方法是什么?

问题描述 投票:2回答:1

问题:我有两个大型列表,有一些重叠的数据。我想从两个列表中较大的一个中减去重叠数据,我在代码中称之为restoredBottles的列表。我使用的第二个较小的列表叫做allBottles。鉴于它们的大小,重新启动我的内循环每次迭代的外环都需要3天才能完成。我需要尝试做一个滑动窗口。

结果我想:循环结束后,我想让列表restoredBottles只包含不重叠的数据。

两个列表按时间戳按升序排序。

for productsAndArchiveIndex, (idx, bcode, tstamp, parentPrepackId, prepackBarcode, tableName) in enumerate(allBottles):
    for restoredDataIndex, (barcode, timestamp, prepack, workorder) in enumerate(restoredBottles):
        # Step 4:  Is this in products+productsArchive_archive?
        if bcode==barcode and tstamp == timestamp and prepackBarcode == prepack:

            # Step 5:  If so, delete it from
            # restoredBottles, if not, move on
            del restoredBottles[restoredDataIndex]
            i = restoredDataIndex - 1
            #Let's shorten this list, we know we are in date order so if we just go back until we hit an earlier time, we can slice it from there
            #If we have room to go backwards
            if i > 0:
                currTimestamp = timestamp
                timeStampToLeft = restoredBottles[i][1]
                #No need to do this towards the end, might only give us a index out of range error
                goodToSlice = False
                while timeStampToLeft >= currTimestamp and i > 0:

                    i -= 1
                    timeStampToLeft = restoredBottles[i][1]
                    goodToSlice = True

                #Then it makes sense to slice
                if i > 0  and goodToSlice:
                    restoredBottles = restoredBottles[i:]

            break
        elif tstamp < timestamp:
            #print(str(tstamp)+ " is farther in the future than "+str(timestamp)+", can stop search")
            #since this is an ordered list, there is no reason to keep searching
            break

我刚刚意识到为什么我的结果太短了,因为我在共享部分之前删除了所有内容,因此我只是得到了restoredBottles列表的尾部。我需要在我的for循环中使用索引,所以我可以删除该项目,但为了使这项工作合理快速,我需要以比开头更合理的索引开始我的第二个for循环(恢复的瓶子大约有250万个项目)很长一段时间,allBottles大概是1.9,所以我应该在一天结束时将大约600,000个装在已修复的瓶子中,写成CSV。任何想法如何做到这一点?

python python-3.x
1个回答
0
投票

可能想尝试将列表转换为“集合”并对它们执行“差异”操作。请记住,设置操作将删除列表中的任何重复项以及订单。

您需要重新排序最终结果。

>>>a = [1, 2, 3, 4, 4]

>>>b = [3, 4, 5, 5, 6]
>>>list(set(a) - set(b))
[1, 2]

python sets

© www.soinside.com 2019 - 2024. All rights reserved.