Dealing with multiple sets

John Henry john106henry at hotmail.com
Thu Oct 26 18:45:07 CEST 2006


Oh, great.  Learn something new everyday.

For this, what I did was to build up a string, and then use eval on the
string.  Very ugly.

Now I can simply do a reduce.

Thanks,



Brian Beck wrote:
> 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