简体   繁体   中英

Why this examples of `zip()` code have different outputs?

As far, as I am able to understand, we are unpacking 3 identical iterators in both cases, but output is different.
In first case, it, for some reason, similar to list(zip(c[::3], c[1::3], c[2::3])) , in second, it behaves like normal zip() .

c = [[a, b] for a, b in itertools.product(list(range(3)), list(range(3)))]

# first example
list(zip(*[iter(c)] * 3))
>[([0, 0], [0, 1], [0, 2]), ([1, 0], [1, 1], [1, 2]), ([2, 0], [2, 1], [2, 2])]

# second example
list(zip(*[iter(c), iter(c), iter(c)]))
>[([0, 0], [0, 0], [0, 0]),
 ([0, 1], [0, 1], [0, 1]),
 ([0, 2], [0, 2], [0, 2]),
 ([1, 0], [1, 0], [1, 0]),
 ([1, 1], [1, 1], [1, 1]),
 ([1, 2], [1, 2], [1, 2]),
 ([2, 0], [2, 0], [2, 0]),
 ([2, 1], [2, 1], [2, 1]),
 ([2, 2], [2, 2], [2, 2])]

your first example is the same as

it = iter(c)
print(list(zip(*[it, it, it])))  # == list(zip(it, it, it))

this is not the same as your second example list(zip(iter(c), iter(c), iter(c)) where you create 3 fresh iterators.

every time next is called on it this has an influence on what happens the next time it is used.

in the second example the 3 iterators run independently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM