How to unzip an iterator?

后端 未结 3 662
南方客
南方客 2021-02-19 10:45

Given a list of pairs xys, the Python idiom to unzip it into two lists is:

xs, ys = zip(*xys)

If xys is an iterator,

3条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 10:58

    Suppose you have some iterable of pairs:

    a = zip(range(10), range(10))
    

    If I'm correctly interpreting what you are asking for, you could generate independent iterators for the firsts and seconds using itertools.tee:

     xs, ys = itertools.tee(a)
     xs, ys = (x[0] for x in xs), (y[1] for y in ys)
    

    Note this will keep in memory the "difference" between how much you iterate one of them vs. the other.

提交回复
热议问题