Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get intersection of list of sets

Tags:

python

list

set

I want python to get the intersection of a list of sets.

For example, I have a function that returns s a list of sets following:

[set(0,1,3), set(1,3)]

As you can see the intersection of this is the set {1,3}. How can I get python to obtain the intersection? What I've been doing so far is iterating over the list. But I can't seen to get the intersection.

Solution should be able to deal with an n element list of sets not just a pair.

Any ideas?

Comprehensions are welcome

As an aside why is the set rendered as set([]) in other words why not just with curly braces?

like image 874
franklin Avatar asked Jul 05 '13 18:07

franklin


2 Answers

Use set.intersection:

>>> lis = [set((0,1,3)), set((1,3))]
>>> set.intersection(*lis)
set([1, 3])

For union use set.union:

>>> set.union(*lis)
set([0, 1, 3])

If performance matters then use this:

>>> from itertools import islice
>>> set.intersection(set(lis[0]), *islice(lis, 1, None))
set([1, 3])
like image 129
Ashwini Chaudhary Avatar answered Sep 21 '22 04:09

Ashwini Chaudhary


Try this:

reduce(set.intersection, L)

In [83]: L = [set([0,1,3]), set([1,3])]

In [84]: reduce(set.intersection, L)
Out[84]: set([1, 3])
like image 22
inspectorG4dget Avatar answered Sep 21 '22 04:09

inspectorG4dget