Why does zip() drop the values of my generator?

前端 未结 2 1892
死守一世寂寞
死守一世寂寞 2021-01-02 04:31

I was writing an answer to this question when noticed that my simple implementation didn\'t produce correct results. While hunting down the bug, I noticed the following:

2条回答
  •  旧时难觅i
    2021-01-02 05:22

    This happens because zip evaluates iterators from left to right, meaning that, after three steps, it calls next() on gen and only then on iter(range(3)) (or something like that) and encounters a StopIteration. To get around this, use the shorter (finite) iterable as the left-most argument:

    In [8]: zip(range(3), gen)
    0
    1
    2
    Out[8]: [(0, 0), (1, 1), (2, 2)]
    

提交回复
热议问题