You are not logged in.

#1 2009-10-15 16:25:41

battra
Member
From: Earth.US.Illinois.Chicago
Registered: 2006-05-12
Posts: 71

Python Question: union of sets in a list

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

#2 2009-10-15 17:05:17

keenerd
Package Maintainer (PM)
Registered: 2007-02-22
Posts: 647
Website

Re: Python Question: union of sets in a list

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

#3 2009-10-15 18:40:30

battra
Member
From: Earth.US.Illinois.Chicago
Registered: 2006-05-12
Posts: 71

Re: Python Question: union of sets in a list

Thanks a lot.  Much appreciated.


"I know nothing except the fact of my ignorance."
- Socrates

Offline

Board footer

Powered by FluxBB