Python: how to find common values in three lists

匿名 (未验证) 提交于 2019-12-03 08:42:37

问题:

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

回答1:

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.



回答2:

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.

For larger lists, you want to look at the answer provided by @poke



回答3:

For those still stumbling uppon this question, with numpy one can use:

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.

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

or

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!