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

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

returnMatches(a, b)

例如,将返回[5]。


当前回答

另一种更实用的方法是检查列表1 (lst1)和列表2 (lst2)是否相等,其中对象的深度为1,并保持顺序:

all(i == j for i, j in zip(lst1, lst2))   

其他回答

您也可以尝试这样做,将公共元素保存在一个新列表中。

new_list = []
for element in a:
    if element in b:
        new_list.append(element)

使用__and__属性方法也可以。

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

或者简单地

>>> set([1, 2, 3, 4, 5]).__and__(set([9, 8, 7, 6, 5]))
set([5])
>>>    

我更喜欢基于集合的答案,但这里有一个不管怎样都有用的答案

[x for x in a if x in b]
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]

lista =set(a)
listb =set(b)   
print listb.intersection(lista)   
returnMatches = set(['5']) #output 

print " ".join(str(return) for return in returnMatches ) # remove the set()   

 5        #final output 

你可以使用:

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])