Python Iterator and Zip Code

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

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

>>> i = iter(x)
>>> zip(i,i)
[(1, 2), (3, 4)]

Even I can use this syntax to get the same results.

>>> zip(*[i] * 2)
[(1, 2), (3, 4)]

How it works? How does an iterator work with zip(i,i)and zip(*[i] * 2)?

+4
source share
2 answers

An iterator is like a stream of elements. You can only watch items in a stream, one at a time, and you only ever have access to the first item. To look at something in the stream, you need to remove it from the stream, and as soon as you take something from the top of the stream, it copes with the stream perfectly.

zip(i, i), zip . ( , ), . , .

, , zip ( 2 ). 1:

def zip(a, b):
    out = []
    try:
        while True:
            item1 = next(a)
            item2 = next(b)
            out.append((item1, item2))
    except StopIteration:
        return out

, , a b - . next (i ), i .

, zip(i, i) , , zip(*([i] * 2)) . ...

[i] * 2

( 2), i. , zip(*[i, i]) ( , - , 2 ). * - python, python. , python "" , . :

zip(*[i, i])

, :

zip(i, i)

. , zip(i, i) .

1 , , 2 . , zip, , iter , ( ), , ...

+7

, , , "". , zip(i, i) i, i tuple. , .

zip(*[i]*2) list of [i, i] i 2, * , i i zip, , .

0

All Articles