Dealing with multiple sets

Brian Beck exogen at gmail.com
Thu Oct 26 04:06:52 CEST 2006


John Henry wrote:
> What's the cleanest way to say:
> 
> 1) Give me a list of the items that are in all of the sets? (3 in the
> above example)
> 2) Give me a list of the items that are not in all of the sets? (1,2 in
> the above example)
> 
> Thanks,

If you have an arbitrary list of sets, reduce comes in handy:

See this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/476215

py> sets = [set((1, 2, 3)), set((2, 3)), set((1, 3))]
py> reduce(set.intersection, sets)
set([3])

py> reduce(set.union, sets)
set([1, 2, 3])

py> reduce(set.union, sets) - reduce(set.intersection, sets)
set([1, 2])

--
Brian Beck
Adventurer of the First Order



More information about the Python-list mailing list