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

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

其他回答

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

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

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

[x for x in a if x in b]

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

all(i == j for i, j in zip(lst1, lst2))   
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.

下面的解决方案适用于列表项的任何顺序,并且还支持两个列表的长度不同。

import numpy as np
def getMatches(a, b):
    matches = []
    unique_a = np.unique(a)
    unique_b = np.unique(b)
    for a in unique_a:
        for b in unique_b:
            if a == b:
                matches.append(a)
    return matches
print(getMatches([1, 2, 3, 4, 5], [9, 8, 7, 6, 5, 9])) # displays [5]
print(getMatches([1, 2, 3], [3, 4, 5, 1])) # displays [1, 3]