Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -Intersection of multiple lists?

I am playing with python and am able to get the intersection of two lists:

result = set(a).intersection(b) 

Now if d is a list containing a and b and a third element c, is there an built-in function for finding the intersection of all the three lists inside d? So for instance,

d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]] 

then the result should be

[3,4] 
like image 869
Legend Avatar asked Oct 04 '10 04:10

Legend


People also ask

How do you concatenate multiple lists in Python?

You can concatenate multiple lists into one list by using the * operator. For Example, [*list1, *list2] – concatenates the items in list1 and list2 and creates a new resultant list object. Usecase: You can use this method when you want to concatenate multiple lists into a single list in one shot.

How do I make a loop with multiple lists?

You can simply use a for loop to create n lists. The variable a_i changes as i increments, so it becomes a_1, a_2, a_3 ... and so on. Show activity on this post. there is a way to do that if you want to create variables.


2 Answers

set.intersection(*map(set,d)) 
like image 102
SingleNegationElimination Avatar answered Sep 22 '22 02:09

SingleNegationElimination


for 2.4, you can just define an intersection function.

def intersect(*d):     sets = iter(map(set, d))     result = sets.next()     for s in sets:         result = result.intersection(s)     return result 

for newer versions of python:

the intersection method takes an arbitrary amount of arguments

result = set(d[0]).intersection(*d[1:]) 

alternatively, you can intersect the first set with itself to avoid slicing the list and making a copy:

result = set(d[0]).intersection(*d) 

I'm not really sure which would be more efficient and have a feeling that it would depend on the size of the d[0] and the size of the list unless python has an inbuilt check for it like

if s1 is s2:     return s1 

in the intersection method.

>>> d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]] >>> set(d[0]).intersection(*d) set([3, 4]) >>> set(d[0]).intersection(*d[1:]) set([3, 4]) >>>  
like image 29
aaronasterling Avatar answered Sep 25 '22 02:09

aaronasterling