You are not logged in.
Suppose you have a list of sets in Python:
>> lst = [ set([0, 1]), set([1, 2]) , set([2, 3]) ]
I want the union of the sets. Since, the list will be large, I need it to be very efficient. Normally I'd use reduce() for this:
>> reduce(lambda x, y : x |y, lst)
set([0, 1, 2, 3])
But, how would I do this WITHOUT using reduce()?
I know I could write a simple for loop, but, I wanted it to be as fast as possible (reduce() is pretty fast even with lambda call).
Is it possible to do this with a generator or list comprehension (which are both fast)?
Thanks.
Last edited by battra (2009-10-15 16:41:55)
"I know nothing except the fact of my ignorance."
- Socrates
Offline
The union operation is also a method of set, set.union(). Unlike the infix union "|", the method can take any number of arguments.
big_union = set.union(set([0, 1]), set([1, 2]) , set([2, 3]))
Use * to break a list/tuple apart, so each element becomes a new argument.
big_union = set.union(*lst)
Last edited by keenerd (2009-10-15 17:10:01)
Offline
Thanks a lot. Much appreciated.
"I know nothing except the fact of my ignorance."
- Socrates
Offline