可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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)