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?
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])
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With