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

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

returnMatches(a, b)

例如,将返回[5]。


当前回答

这是为那些可能返回某个字符串或输出的人准备的, 下面是代码,希望能有所帮助:

lis =[]
#convert to list
a = list(data)
b = list(data)
def make_list():
    c = "greater than"
    d = "less_than"
    e = "equal"
    for first, first_te in zip(a, b):
        if first < first_te:
            lis.append(d)
        elif first > first_te:
            lis.append(c)
        else:
            lis.append(e)
    return lis

make_list()

其他回答

你要复印一份吗?如果不是,也许你应该使用集合:

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

快捷方式:

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

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

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

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

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]

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

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