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

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

其他回答

这不是最有效的方法,但到目前为止最明显的方法是:

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

如果顺序很重要,你可以用这样的列表推导式来做:

>>> [i for i, j in zip(a, b) if i == j]
[5]

(仅适用于同等大小的列表,这意味着顺序重要性)。

你可以使用

def returnMatches(a,b):
       return list(set(a) & set(b))

最简单的方法是使用set:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(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

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

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