我试图比较两个列表并获取新元素,包括冗余元素。 例如,结果:
l1 = [1,2,3,3,4]
l2 = [3,3,3,4,4,5,6]
是:
l2 - l1 = [3,4,5,6]
您可以很容易地理解我无法使用set进行操作,因为
set(l1) = (1,2,3,4)
set(l2) = (3,4,5,6)
结果将是:(5,6)
我不想通过
这样的迭代来做这件事[i for i in l1 if i not in l2 ]
因为它太慢了(参见Get difference between two lists的基准测试)
有没有人知道如何在没有迭代的情况下完成它并保持冗余元素或迭代方法是唯一的方法?
谢谢!
解决方案的基准测试:
我对两个给定的解决方案进行了基准测试,结果如下:
import random
init1 = list(range(10000))
init2 = [i*random.randint(1,50) for i in range(10000)]
# Put both solution in function, diff1 = remove method, diff2 = Counter method
import time
tic1 = time.clock()
print(diff1(init2,init1))
toc1 = time.clock()
tic2 = time.clock()
print(diff2(init2,init1))
toc2 = time.clock()
print(toc1-tic1)
print(toc2-tic2)
结果是:
2.756271607145601 for diff1
0.028116911506909315 for diff2
答案 0 :(得分:4)
您正在寻找multisets,这正是collections.Counter
的用途:
>>> from collections import Counter
>>> list((Counter(l2) - Counter(l1)).elements())
[3, 4, 5, 6]
答案 1 :(得分:1)
您可以按照以下方式执行此操作:
l1 = [1,2,3,3,4]
l2 = [3,3,3,4,4,5,6]
l3 = l1[:]
l4 = l2[:]
for item in l2:
if item in l3:
l3.remove(item)
l4.remove(item)
>>> print l4
[3,4,5,6]