我想取两个列表,并找出出现在这两个列表中的值。
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)))
其他回答
你要复印一份吗?如果不是,也许你应该使用集合:
>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
set([5])
我更喜欢基于集合的答案,但这里有一个不管怎样都有用的答案
[x for x in a if x in b]
使用set.intersection(),它快速且可读。
>>> set(a).intersection(b)
set([5])
如果你想要一个布尔值:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b)
False
>>> a = [3,1,2]
>>> b = [1,2,3]
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b)
True
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.