more fun with iterators (mux, demux)
steven at REMOVE.THIS.cybersource.com.au
Tue Apr 7 04:05:59 CEST 2009
On Mon, 06 Apr 2009 20:05:51 -0400, Neal Becker wrote:
> I'm trying to make a multiplexor and demultiplexor, using generators.
> The multiplexor will multiplex N sequences -> 1 sequence (assume equal
> length). The demultiplexor will do the inverse.
> The mux seems easy enough:
> def mux (*ranges):
> iterables = [iter (r) for r in ranges] while (True):
> for i in (iterables):
> yield i.next()
This is like a zip, and can be re-written using itertools.izip.
for i in itertools.izip(*iterables):
for item in i:
The demuxer can't be an iterator, since it needs to run through the
def demux(it, n):
collectors = [ for i in xrange(n)]
i = 0
for item in it:
i = (i+1) % n
return tuple([iter(x) for x in collectors])
More information about the Python-list