我想取两个列表,并找出出现在这两个列表中的值。

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]

returnMatches(a, b)

例如,将返回[5]。


当前回答

使用set.intersection(),它快速且可读。

>>> set(a).intersection(b)
set([5])

其他回答

快捷方式:

list(set(a).intersection(set(b)))

使用set.intersection(),它快速且可读。

>>> set(a).intersection(b)
set([5])

我使用了下面的方法,它对我很有效:

group1 = [1, 2, 3, 4, 5]
group2 = [9, 8, 7, 6, 5]

for k in group1:
    for v in group2:
        if k == v:
            print(k)

在你的例子中,这会输出5。可能不是很好的性能。

你可以使用:

a = [1, 3, 4, 5, 9, 6, 7, 8]
b = [1, 7, 0, 9]
same_values = set(a) & set(b)
print same_values

输出:

set([1, 7, 9])

最简单的方法是使用set:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
set([5])