Python:如何在三个列表中找到公共值 [英] Python: how to find common values in three lists

查看:65
本文介绍了Python:如何在三个列表中找到公共值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试为三个不同的列表找到共同的值列表:

a = [1,2,3,4]b = [2,3,4,5]c = [3,4,5,6]

当然,我尝试使用 and 运算符,但是这样我只会得到表达式中最后一个 list 的值:

<代码>>>a 和 b 和 c出:[3,4,5,6]

有没有找到通用值列表的捷径:

[3,4]

Br

解决方案

使用集合:

<预><代码>>>>a = [1, 2, 3, 4]>>>b = [2, 3, 4, 5]>>>c = [3, 4, 5, 6]>>>设置(a) &设置(b) &设置(c){3, 4}

或者像乔恩建议的那样:

<预><代码>>>>设置(a).交集(b,c){3, 4}

使用集合的好处是不需要重复迭代原始列表.每个列表迭代一次以创建集合,然后将集合相交.

像 Geotob 那样使用过滤列表推导式来解决这个问题的天真方法是为 a 的每个元素迭代列表 bc,所以对于更长的列表,这会降低很多效率.

I try to find common list of values for three different lists:

a = [1,2,3,4]
b = [2,3,4,5]
c = [3,4,5,6]

of course naturally I try to use the and operator however that way I just get the value of last list in expression:

>> a and b and c
out: [3,4,5,6]

Is any short way to find the common values list:

[3,4]

Br

解决方案

Use sets:

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

Or as Jon suggested:

>>> set(a).intersection(b, c)
{3, 4}

Using sets has the benefit that you don’t need to repeatedly iterate the original lists. Each list is iterated once to create the sets, and then the sets are intersected.

The naive way to solve this using a filtered list comprehension as Geotob did will iterate lists b and c for each element of a, so for longer list, this will be a lot less efficient.

这篇关于Python:如何在三个列表中找到公共值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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