我想取两个列表,并找出出现在这两个列表中的值。
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]。
当前回答
另一种更实用的方法是检查列表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.
>>> 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'])**
你可以使用
def returnMatches(a,b):
return list(set(a) & set(b))
您也可以尝试这样做,将公共元素保存在一个新列表中。
new_list = []
for element in a:
if element in b:
new_list.append(element)
另一种更实用的方法是检查列表1 (lst1)和列表2 (lst2)是否相等,其中对象的深度为1,并保持顺序:
all(i == j for i, j in zip(lst1, lst2))