簡體   English   中英

快速刪除包含其他列表元組的元組

[英]Quickly remove tuples that contain tuples of other list

我想刪除列表 A 中包含列表 B 中的元組的所有元組。

這通常是一件小事,但我在列表 A 中有 1000 萬條記錄,在列表 B 中有 20 萬條記錄。我當前的腳本(見下文)非常慢(每次掃描列表 A 約 10 秒)。

例子:

# Input:
listA = [(1,2,3,4,5),(1,2,4,5,6),(1,2,3,7,55),(8,21,22,24,37),...]  # 10 million records
listB = [(1,2,4),(1,4,6),(21,24,37),...]  # 200K records

# Desired Output (filtered listA):
listA = [(1,2,3,7,55),...]

當前的腳本很慢:

listA=[(1,2,3,4,5),(1,2,4,5,6),(1,2,3,7,55),(8,21,22,24,37)]
listB=[(1,2,4),(1,4,6),(21,24,37)]
listATemp=[]

for b in listB:
  for a in listA:
    if not set(b).issubset(a) :
      listATemp.append(a)
  listA= listATemp
  listATemp= []

使用itertools.combinationsfrozenset

setB = set(map(frozenset, listB))
n = len(listB[0])
listA = [a for a in listA if not any(frozenset(c) in setB for c in combinations(a, n))]

或者假設每個元組都已排序(如果沒有,您當然可以先對它們進行排序):

setB = set(listB)
n = len(listB[0])
listA = [a for a in listA if setB.isdisjoint(combinations(a, n))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM