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

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

returnMatches(a, b)

例如,将返回[5]。


当前回答

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.

其他回答

>>> s = ['a','b','c']   
>>> f = ['a','b','d','c']  
>>> ss= set(s)  
>>> fs =set(f)  
>>> print ss.intersection(fs)   
   **set(['a', 'c', 'b'])**  
>>> print ss.union(fs)        
   **set(['a', 'c', 'b', 'd'])**  
>>> print ss.union(fs)  - ss.intersection(fs)   
   **set(['d'])**

最简单的方法是使用set:

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

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

>>> set(a).intersection(b)
set([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()

你可以使用

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