Python:如何在三个列表中找到公共值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28061223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: how to find common values in three lists
提问by Magnar
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
表达式中 last 的值:
>> a and b and c
out: [3,4,5,6]
Is any short way to find the common values list:
找到通用值列表的任何捷径:
[3,4]
Br
溴
采纳答案by poke
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 那样使用过滤列表理解来解决这个问题的天真方法将迭代列表b
和c
的每个元素a
,因此对于更长的列表,这将降低效率。
回答by Geotob
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
b
c
For larger lists, you want to look at the answer provided by @poke
对于较大的列表,您需要查看@poke 提供的答案
回答by L. IJspeert
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.
It could be extended to more arrays with the help of functools.reduce
, or it can simply be repeated for several arrays.
这适用于列表以及 numpy 数组。它可以在 的帮助下扩展到更多数组functools.reduce
,或者可以简单地对多个数组重复。
from functools import reduce
reduce(np.intersect1d, (array1, array2, array3))
or
或者
new_array = np.intersect1d(array1, array2)
np.intersect1d(new_array, array3)