如何比较python中的两个列表并返回匹配项 [英] How can I compare two lists in python and return matches

查看:240
本文介绍了如何比较python中的两个列表并返回匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想列出两个列表,并找到同时出现在两个列表中的值.

I want to take two lists and find the values that appear in both.

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

returnMatches(a, b)

例如,

将返回[5].

推荐答案

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

Not the most efficient one, but by far the most obvious way to do it is:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}

如果顺序很重要,则可以使用以下列表理解来实现:

if order is significant you can do it with list comprehensions like this:

>>> [i for i, j in zip(a, b) if i == j]
[5]

(仅适用于大小相等的列表,这意味着顺序意义).

(only works for equal-sized lists, which order-significance implies).

这篇关于如何比较python中的两个列表并返回匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆