如何比较python中的两个列表并返回匹配项
我想获取两个列表并找到两者中出现的值。
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
returnMatches(a, b)
例如,将返回[5]。
tehryan asked 2019-02-05T22:05:16Z
19个解决方案
357 votes
不是最有效的方法,但到目前为止最明显的方法是:
>>> 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]
(仅适用于大小相同的列表,其中含义为重要性)。
SilentGhost answered 2019-02-05T22:05:36Z
301 votes
使用set.intersection(),它快速且可读。
>>> set(a).intersection(b)
set([5])
Dennis answered 2019-02-05T22:05:58Z
77 votes
快速性能测试显示Lutz的解决方案是最好的:
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 i