I have a list of sets:
setlist = [s1,s2,s3...]
I want s1 ∩ s2 ∩ s3 ...
I can write a function to do it by performing a series of pairwise s1.intersection(s2)
, etc.
Is there a recommended, better, or built-in way?
I have a list of sets:
setlist = [s1,s2,s3...]
I want s1 ∩ s2 ∩ s3 ...
I can write a function to do it by performing a series of pairwise s1.intersection(s2)
, etc.
Is there a recommended, better, or built-in way?
If you don't have Python 2.6 or higher, the alternative is to write an explicit for loop:
You can also use
reduce
:However, many Python programmers dislike it, including Guido himself:
From Python version 2.6 on you can use multiple arguments to
set.intersection()
, likeIf the sets are in a list, this translates to:
where
*a_list
is list expansionHere I'm offering a generic function for multiple set intersection trying to take advantage of the best method available:
Guido might dislike
reduce
, but I'm kind of fond of it :)Clearly
set.intersection
is what you want here, but in case you ever need a generalisation of "take the sum of all these", "take the product of all these", "take the xor of all these", what you are looking for is thereduce
function:or
As of 2.6,
set.intersection
takes arbitrarily many iterables.