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

如何比较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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值