如何比较python中的两个列表并返回匹配

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

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


returnMatches(a, b)

将返回[5],例如。

1397317 次浏览

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

>>> 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]
>>> set(a) & set(b)
set([5])

使用set.intersection (),它是快速和可读的。

>>> set(a).intersection(b)
set([5])

快捷方式:

list(set(a).intersection(set(b)))

你要复印一份吗?如果不是,也许你应该使用集合:

>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
set([5])

你可以使用

def returnMatches(a,b):
return list(set(a) & set(b))
>>> 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'])**

我更喜欢基于集合的答案,但这里有一个不管怎样都有用的答案

[x for x in a if x in b]

您也可以尝试这样做,将公共元素保存在一个新列表中。

new_list = []
for element in a:
if element in b:
new_list.append(element)

一个快速的性能测试显示卢茨的解决方案是最好的:

import time


def speed_test(func):
def wrapper(*args, **kwargs):
t1 = time.time()
for x in xrange(5000):
results = func(*args, **kwargs)
t2 = time.time()
print '%s took %0.3f ms' % (func.func_name, (t2-t1)*1000.0)
return results
return wrapper


@speed_test
def compare_bitwise(x, y):
set_x = frozenset(x)
set_y = frozenset(y)
return set_x & set_y


@speed_test
def compare_listcomp(x, y):
return [i for i, j in zip(x, y) if i == j]


@speed_test
def compare_intersect(x, y):
return frozenset(x).intersection(y)


# Comparing short lists
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)


# Comparing longer lists
import random
a = random.sample(xrange(100000), 10000)
b = random.sample(xrange(100000), 10000)
compare_bitwise(a, b)
compare_listcomp(a, b)
compare_intersect(a, b)

这是我的机器上的结果:

# Short list:
compare_bitwise took 10.145 ms
compare_listcomp took 11.157 ms
compare_intersect took 7.461 ms


# Long list:
compare_bitwise took 11203.709 ms
compare_listcomp took 17361.736 ms
compare_intersect took 6833.768 ms

显然,任何人工性能测试都应持保留态度,但由于set().intersection()答案与其他解决方案一样是至少一样快,而且也是最易读的,因此它应该是这个常见问题的标准解决方案。

你可以使用:

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

另一种更实用的方法是检查列表1 (lst1)和列表2 (lst2)是否相等,其中对象的深度为1,并保持顺序:

all(i == j for i, j in zip(lst1, lst2))

可以使用itertools。产品。

>>> 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]
>>> 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

使用__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])
>>>
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

下面的解决方案适用于列表项的任何顺序,并且还支持两个列表的长度不同。

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]
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.

我使用了下面的方法,它对我很有效:

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

还有一个找到共同价值观的方法:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
matches = [i for i in a if i in b]