inverse of izip
Satchidanand Haridas
sharidas at zeomega.com
Thu Aug 19 03:48:24 EDT 2004
Hi,
How about using iter() to get another solution like the following:
>>> starzip2 = lambda it: tuple([iter(x) for x in itertools.izip(*it)])
>>> l,m = starzip2(itertools.izip(range(10),range(10)))
>>> l
<tupleiterator object at 0x4016802c>
>>> m
<tupleiterator object at 0x4016896c>
>>> list(l)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(m)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Thanks,
Satchit
----
Satchidanand Haridas (sharidas at zeomega dot com)
ZeOmega (www.zeomega.com)
Open Minds' Open Solutions
#20,Rajalakshmi Plaza,
South End Road,
Basavanagudi,
Bangalore-560 004, India
Steven Bethard wrote:
>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