如何检查列表中是否有以下项目之一?我试图找到一个简短的方法来查看列表中是否有以下任何项目,但我的第一次尝试不起作用。除了编写一个完成此功能的函数之外,还有一种简短的方法可以检查列表中是否存在多个项目之一。>>> a = [2,3,4]>>> print (1 or 2) in aFalse>>> print (2 or 1) in aTrue
3 回答

陪伴而非守候
TA贡献1757条经验 获得超8个赞
>>> L1 = [2,3,4]
>>> L2 = [1,2]
>>> [i for i in L1 if i in L2]
[2]
>>> S1 = set(L1)
>>> S2 = set(L2)
>>> S1.intersection(S2)
set([2])
空列表和空集都是False,因此您可以直接将该值用作真值。

哈士奇WWW
TA贡献1799条经验 获得超6个赞
我不得不说我的情况可能不是你想要的,但它可能会提供你的想法的替代方案。
我已经尝试了set()和any()方法,但仍然存在速度问题。所以我记得Raymond Hettinger说python中的所有内容都是字典,并且只要你能使用dict就可以使用dict。这就是我的尝试。
我使用带有int的defaultdict来表示否定结果,并使用第一个列表中的项作为第二个列表的键(转换为defaultdict)。因为您可以使用dict进行即时查找,所以您可以立即知道该项是否存在于defaultdict中。我知道你并不总是为第二个列表更改数据结构,但是如果你能够从一开始就能够更快,那么它就会更快。您可能必须将list2(较大列表)转换为defaultdict,其中key是您要从小列表中检查的潜在值,value是1(hit)或0(no hit,default)。
from collections import defaultdict already_indexed = defaultdict(int)def check_exist(small_list, default_list): for item in small_list: if default_list[item] == 1: return True return Falseif check_exist(small_list, already_indexed): continueelse: for x in small_list: already_indexed[x] = 1
添加回答
举报
0/150
提交
取消