简体   繁体   English

Python:如何在三个列表中查找常用值

[英]Python: how to find common values in three lists

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: 当然我自然会尝试使用and运算符,但是这样我只得到表达式中最后一个list的值:

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

Is any short way to find the common values list: 有没有找到常用值列表的简短方法:

[3,4]

Br 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. 用简单的方式来解决这个使用的过滤列表理解为Geotob确实会遍历表bc的每个元素a ,所以对于较长的名单,这将是少了很多有效的。

out = [x for x in a if x in b and x in c]

is a quick and simple solution. 是一个快速而简单的解决方案。 This constructs a list out with entries from a , if those entries are in b and c . 这构建了一个清单out与项目a ,如果这些条目是在bc

For larger lists, you want to look at the answer provided by @poke 对于较大的列表,您需要查看@poke提供的答案

For those still stumbling uppon this question, with numpy one can use: 对于仍然在这个问题上磕磕绊绊的人来说,numpy可以使用:

np.intersect1d(array1, array2)

This works with lists as well as numpy arrays. 这适用于列表以及numpy数组。 It could be extended to more arrays with the help of functools.reduce , or it can simply be repeated for several arrays. 它可以在functools.reduce的帮助下扩展到更多的数组,或者它可以简单地重复几个数组。

from functools import reduce
reduce(np.intersect1d, (array1, array2, array3))

or 要么

new_array = np.intersect1d(array1, array2)
np.intersect1d(new_array, array3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM