Python iterator and zip

前端 未结 2 1321
渐次进展
渐次进展 2020-12-10 17:49

With x = [1,2,3,4], I can get an iterator from i = iter(x).

With this iterator, I can use zip function to create a tuple with two items.

2条回答
  •  感动是毒
    2020-12-10 18:03

    Every time you get an item from an iterator, it stays at that spot rather than "rewinding." So zip(i, i) gets the first item from i, then the second item from i, and returns that as a tuple. It continues to do this for each available pair, until the iterator is exhausted.

    zip(*[i]*2) creates a list of [i, i] by multiplying i by 2, then unpacks it with the * at the far left, which, in effect, sends two arguments i and i to zip, producing the same result as the first snippet.

提交回复
热议问题