我想取两个列表,并找出出现在这两个列表中的值。
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]
returnMatches(a, b)
例如,将返回[5]。
当前回答
你可以使用:
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])
其他回答
这不是最有效的方法,但到目前为止最明显的方法是:
>>> 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]
(仅适用于同等大小的列表,这意味着顺序重要性)。
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
快捷方式:
list(set(a).intersection(set(b)))
你可以使用
def returnMatches(a,b):
return list(set(a) & set(b))
可以使用itertools。产品。
>>> common_elements=[]
>>> for i in list(itertools.product(a,b)):
... if i[0] == i[1]:
... common_elements.append(i[0])