Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create the union of many sets using a generator expression?

Suppose I have a list of sets and I want to get the union over all sets in that list. Is there any way to do this using a generator expression? In other words, how can I create the union over all sets in that list directly as a frozenset?

like image 240
Björn Pollex Avatar asked Aug 09 '10 07:08

Björn Pollex


People also ask

How do you find the union of multiple sets?

The most efficient way to join multiple sets (stored in a list of sets), use the Python one-liner set(). union(*list) that creates a new set object, calls the union() method on the new object, and unpacks all sets from the list of sets into the union() method's argument list.


2 Answers

Just use the .union() method.

>>> l = [set([1,2,3]), set([4,5,6]), set([1,4,9])] >>> frozenset().union(*l) frozenset([1, 2, 3, 4, 5, 6, 9]) 

This works for any iterable of iterables.

like image 124
kennytm Avatar answered Sep 22 '22 04:09

kennytm


I assume that what you're trying to avoid is the intermediate creations of frozenset objects as you're building up the union?

Here's one way to do it. NOTE: this originally used itertools.chain() but, as Kenny's comment notes, the version below is slightly better:

import itertools  def mkunion(*args):     return frozenset(itertools.chain.from_iterable(args)) 

Invoke like this:

a = set(['a','b','c']) b = set(['a','e','f']) c = mkunion(a,b)       # => frozenset(['a', 'c', 'b', 'e', 'f']) 
like image 28
Owen S. Avatar answered Sep 21 '22 04:09

Owen S.