inverse of izip

Steven Bethard steven.bethard at gmail.com
Thu Aug 19 03:31:25 EDT 2004


Steven Bethard <steven.bethard <at> gmail.com> writes:
> What's the inverse of izip?  Of course, I could use zip(*) or izip(*),
> e.g.:
> 
> >>> zip(*itertools.izip(range(10), range(10)))
> [(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)]
> >>> x, y = itertools.izip(*itertools.izip(range(10), range(10)))
> >>> x, y
> ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (0, 1, 2, 3, 4, 5, 6, 7, 8, 9))
> 
> But then I get a pair of tuples, not a pair of iterators.  Basically,
> I want to convert an iterator of tuples into a tuple of iterators.

Sorry to respond to myself, but after playing around with itertools for a 
while, this seems to work:

>>> import itertools
>>> starzip = lambda iterables: ((tuple[i] for tuple in itr) for i, itr in 
enumerate(itertools.tee(iterables)))
>>> starzip(itertools.izip(range(10), range(10)))
<generator object at 0x008DED28>
>>> x, y = starzip(itertools.izip(range(10), range(10)))
>>> x
<generator object at 0x008E1058>
>>> y
<generator object at 0x008E1080>
>>> list(x)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(y)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Seems like a bit of work for the inverse of izip though so I'll wait to see if 
anyone else has a better solution.  (Not to mention, it wouldn't be a single 
line solution if I wasn't using 2.4...)

Steve





More information about the Python-list mailing list