more fun with iterators (mux, demux)
Miles
semanticist at gmail.com
Mon Apr 6 23:35:25 EDT 2009
On Mon, Apr 6, 2009 at 10:05 PM, Steven D'Aprano wrote:
> 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.
>
> def mux(*iterables):
> for i in itertools.izip(*iterables):
> for item in i:
> yield item
In Python 2.6, you could also do this:
def mux(*iterables):
return itertools.chain.from_iterable(itertools.izip(*iterables))
-Miles
More information about the Python-list
mailing list