I tried to implement the inverse function itertools.izip on Python 2.7.1. The fact is that I find a problem, and I have no explanation. Solution 1, iunzip_v1 works fine. But solution 2. iunzip_v2 does not work as expected. So far I have not found any important information about this problem and have read PEP about generators, it sounds like this should work, but it is not.
import itertools from operator import itemgetter def iunzip_v1(iterable): _tmp, iterable = itertools.tee(iterable, 2) iters = itertools.tee(iterable, len(_tmp.next())) return tuple(itertools.imap(itemgetter(i), it) for i, it in enumerate(iters)) def iunzip_v2(iterable): _tmp, iterable = itertools.tee(iterable, 2) iters = itertools.tee(iterable, len(_tmp.next())) return tuple((elem[i] for elem in it) for i, it in enumerate(iters))
result:
In [17]: l Out[17]: [(0, 0, 0), (1, 2, 3), (2, 4, 6), (3, 6, 9), (4, 8, 12)] In [18]: map(list, iunzip.iunzip_v1(l)) Out[18]: [[0, 1, 2, 3, 4], [0, 2, 4, 6, 8], [0, 3, 6, 9, 12]] In [19]: map(list, iunzip.iunzip_v2(l)) Out[19]: [[0, 3, 6, 9, 12], [0, 3, 6, 9, 12], [0, 3, 6, 9, 12]]
It seems that iunzip_v2 uses the last value, so generators do not store the value while they are created inside the first generator. Something is missing for me, and I do not know what it is.
Thanks in advance if something can clarify this situation for me.
UPDATE: I found an explanation here of PEP-289 , my first reading was on PEP-255. The solution I'm trying to implement is lazy, therefore:
zip(*iter) or izip(*...)
doesn't work for me because * arg extends the argument list.