我想取两个列表,并找出出现在这两个列表中的值。
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
例如,将返回[5]。
我想取两个列表,并找出出现在这两个列表中的值。
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
例如,将返回[5]。
当前回答
快捷方式:
list(set(a).intersection(set(b)))
其他回答
you can | for set union and & for set intersection.
for example:
set1={1,2,3}
set2={3,4,5}
print(set1&set2)
output=3
set1={1,2,3}
set2={3,4,5}
print(set1|set2)
output=1,2,3,4,5
curly braces in the answer.
另一种更实用的方法是检查列表1 (lst1)和列表2 (lst2)是否相等,其中对象的深度为1,并保持顺序:
all(i == j for i, j in zip(lst1, lst2))
使用set.intersection(),它快速且可读。
>>> set(a).intersection(b)
set([5])
我更喜欢基于集合的答案,但这里有一个不管怎样都有用的答案
[x for x in a if x in b]
最简单的方法是使用set:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
set([5])