Python: how to find common values ​​in three lists

I am trying to find a common list of values ​​for three different lists:

a = [1,2,3,4] b = [2,3,4,5] c = [3,4,5,6] 
Naturally, I try to use the and operator, however, this way I just get the value of the last list in the expression:
 >> a and b and c out: [3,4,5,6] 

Is there a short way to search for a list of common values:

 [3,4] 

Vg

+6
source share
3 answers

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 John suggested:

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

Using sets has the advantage that you do not need to repeat the original lists. Each list is repeated once to create sets, and then sets intersect.

A naive way to solve this problem using a filtered list, as Geotob did, would result in repeating lists b and c for each element a , so this would be much less efficient for a longer list.

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

- quick and easy solution. This creates an out list with entries from a if these entries are in b and c .

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

+8
source

For those who are still stumbling over this question, with numpy you can use:

 np.intersect1d(array1, array2) 

This works with lists as well as with numpy arrays. It can be expanded to more arrays with functools.reduce , or it can simply be repeated for multiple arrays.

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

or

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

Source: https://habr.com/ru/post/981332/


All Articles