【问题标题】:Quickly remove tuples that contain tuples of other list快速删除包含其他列表元组的元组
【发布时间】:2020-08-01 20:40:57
【问题描述】:

我想删除列表 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= []

【问题讨论】:

  • A 元素中的项目是否总是唯一的? B 的元素总是三元组吗?对此进行优化将取决于特定的约束和先决条件。
  • 是的,两个列表中的元素都是唯一的。是的,B 的元素总是三元组。请注意,我的真实示例在列表 B 中有 5 个元组,在列表 A 中有 7 个元组,但我在这里对其进行了简化以使其更易于理解。另外,感谢您的编辑。
  • listA 和 listB 中的元组是否总是有序的?

标签: python for-loop tuples subset data-transform


【解决方案1】:

使用itertools.combinations 和frozenset:

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))]

【讨论】:

  • 这就是我的想法——如果 OP 的元组真的排序了,就不需要 freezesets。
  • @superb rain - 干得好!谢谢! :) 本来需要几天才能运行的东西现在在几分钟内就完成了!
  • @jonrsharpe 对。为此添加了一个版本。
  • @FirstRedPepper 刚刚加了一个,可能会快一点。
  • 我怀疑保留any 会比不相交的any(c in setB for c in combinations(a, n)) 更有效。 @FirstRedPepper 总加速是 O(len(listA) * len(listB)) -> O(len(listA)),非常可观,加上使用列表解析而不是附加到最初为空的列表,可以节省大量列表调整大小。
猜你喜欢
  • 2017-08-19
  • 2016-09-25
  • 1970-01-01
  • 1970-01-01
  • 2013-04-07
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多