![](/img/trans.png)
[英]Is there a better way to compare two lists in Python, stopping at the shorter list?
[英]Python: Better way to compare two lists?
请不要给我减号。 我想问一个更好的方法来解决这个问题,因为我现在正在做的事情对我来说已成为沉重的负担。
嗨,我的问题是:我有两个清单。 我要确保一个列表中没有项目在另一个列表中。
在Python中,我一直在处理以下几行...(假设List_s有3个项。)
if List_s[0] not in List_big and List_s[1] not in List_big and List_s[2] not in List_big: #none item from List_s should be in List_big
do something
else:
pass
这些行对我来说实际上是可以的,直到我突然意识到必须使用长度大于200的列表。 我有很多要比较的清单。
那么我该如何更改代码? 非常感谢您的帮助!
您可以将列表之一转换为set
然后使用set.intersection
:
if not set(List_s).intersection(List_big):
print('no common items between lists')
请注意,两个列表中的元素都必须是可哈希的 。
无论使用以下哪种方法,您都将获得相同的结果:
set(List_s).isdisjoint(List_big)
要么:
not set(List_s).intersection(List_big)
但是set.isdisjoint更快。 在我的计算机上, isdisjoint
大约需要150纳秒才能运行测试数据,而intersection
需要95微秒才能运行相同数据-慢630倍!
对于非常大的清单,
import timeit
import random
L=[random.randrange(2000000) for x in xrange(1000000)]
M=[random.randrange(2000000) for x in xrange(1000000)]
start_time = timeit.default_timer()
print any(x in M for x in L)
#True
print timeit.default_timer() - start_time
#0.00981207940825
start_time = timeit.default_timer()
print not set(L).isdisjoint(M)
#True
print timeit.default_timer() - start_time
#0.164795298542
start_time = timeit.default_timer()
print True if set(L) & set(M) else False
#True
print timeit.default_timer() - start_time
#0.436377859225
start_time = timeit.default_timer()
print True if set(L).intersection(M) else False
#True
print timeit.default_timer() - start_time
#0.368563831022
显然,
print any(x in M for x in L)
更有效率
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.