我在Python中有两个列表,如下所示:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']我需要用第一个列表中没有出现在第二个列表中的条目创建第三个列表。从这个例子中,我必须得到
temp3 = ['Three', 'Four']有没有不需要循环和检查的快速方法?
发布于 2010-08-12 03:40:01
要获取temp1中但不在temp2 中的元素:
In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']请注意,它是非对称 :
In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1]) 您可能希望/希望它等于set([1, 3])。如果你确实想要set([1, 3])作为你的答案,你可以使用set([1, 2]).symmetric_difference(set([2, 3]))。
发布于 2010-08-12 03:44:48
现有的解决方案都提供以下两种解决方案之一:
输入列表的顺序比O(n*m) performance.
但到目前为止,还没有一种解决方案同时具备这两种功能。如果你想两者兼得,试试这个:
s = set(temp2)
temp3 = [x for x in temp1 if x not in s]性能测试
import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)
print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)
print timeit.timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)结果:
4.34620224079 # ars' answer
4.2770634955 # This answer
30.7715615392 # matt b's answer我提出的方法以及保持顺序也比集合减法(略)快,因为它不需要构造不必要的集合。如果第一个列表比第二个列表长得多,并且哈希开销很大,那么性能差异将更加明显。下面是演示这一点的第二个测试:
init = '''
temp1 = [str(i) for i in range(100000)]
temp2 = [str(i * 2) for i in range(50)]
'''结果:
11.3836875916 # ars' answer
3.63890368748 # this answer (3 times faster!)
37.7445402279 # matt b's answer发布于 2016-07-07 15:50:04
可以使用python XOR运算符来完成。
set(temp1) ^ set(temp2)https://stackoverflow.com/questions/3462143
复制相似问题