我想要取两个列表中共同出现的值。
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]
。
也可以使用itertools.product。
>>> common_elements=[]
>>> for i in list(itertools.product(a,b)):
... if i[0] == i[1]:
... common_elements.append(i[0])
找到共同值的另一种方法:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
matches = [i for i in a if i in b]
您可以使用:
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])
标签
。def returnMatches(a,b):
return list(set(a) & set(b))
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
>>> 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
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]
np.intersect1d(list1, list2)
。 - obchardon__and__
属性方法也可以。>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a).__and__(set(b))
set([5])
>>> set([1, 2, 3, 4, 5]).__and__(set([9, 8, 7, 6, 5]))
set([5])
>>>
我刚刚使用了以下代码,它对我有效:
group1 = [1, 2, 3, 4, 5]
group2 = [9, 8, 7, 6, 5]
for k in group1:
for v in group2:
if k == v:
print(k)
这将在您的情况下打印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()