I have a list of lists, like follow:
list = [[1,2,3],[2,3,4],[3,4,5],[3,5,6]]
I want to find the intersection of them in python 2.7, I mean
intersect_list = [3]
Thanks.
I have a list of lists, like follow:
list = [[1,2,3],[2,3,4],[3,4,5],[3,5,6]]
I want to find the intersection of them in python 2.7, I mean
intersect_list = [3]
Thanks.
First, don't use list as a variable name - it hides the built in class.
Next, this will do it
>>> a = [[1,2,3],[2,3,4],[3,4,5],[3,5,6]]
>>> set.intersection(*map(set,a))
{3}
The map(set,a) simply converts it to a list of sets. Then you just unpack the list and find the intersection.
If you really need the result as a list, just wrap the call with list(...)
set(a[0]).intersection(*a[1:]) which would avoid needing to convert most of the lists to sets.set(m[0]).intersection(*m[1:]) for refusing of converting all the sublists to set.