python - 在没有设置的情况下更快地获得两个列表的差异

标签 python performance list difference

我正在尝试比较两个列表并获取新元素,包括冗余元素。 例如,结果:

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

最佳答案

您正在寻找 multisets ,这正是 collections.Counter用于:

>>> from collections import Counter
>>> list((Counter(l2) - Counter(l1)).elements())
[3, 4, 5, 6]

关于python - 在没有设置的情况下更快地获得两个列表的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782185/

相关文章:

scala - Spark 窗口分区功能将永远完成

linux - 确定在 linux 中读取文件的最佳缓冲区大小

python - Visual Studio Code - Python - 列表索引限制最大 300 - 调试器

java - 如何从另一个 Activity 访问 fragment 列表?

c# - List inside list 不打印元素,而是显示 System.Collections.Generic.List`1[System.Object]

python - 将行值重复 X 次

python - 模板中的删除按钮处于非事件状态

Python字符串操作——性能问题

python - Ubuntu pyautogui .screenshot() 返回黑屏图像

python - 为什么 Flask SQL Alchemy 允许保存 None 主键?