How does zip(*[iter(s)]*n) work in Python?

后端 未结 6 1439
渐次进展
渐次进展 2020-11-22 05:55
s = [1,2,3,4,5,6,7,8,9]
n = 3

zip(*[iter(s)]*n) # returns [(1,2,3),(4,5,6),(7,8,9)]

How does zip(*[iter(s)]*n) work? What would it l

6条回答
  •  盖世英雄少女心
    2020-11-22 06:13

    I think one thing that's missed in all the answers (probably obvious to those familiar with iterators) but not so obvious to others is -

    Since we have the same iterator, it gets consumed and the remaining elements are used by the zip. So if we simply used the list and not the iter eg.

    l = range(9)
    zip(*([l]*3)) # note: not an iter here, the lists are not emptied as we iterate 
    # output 
    [(0, 0, 0), (1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5), (6, 6, 6), (7, 7, 7), (8, 8, 8)]
    

    Using iterator, pops the values and only keeps remaining available, so for zip once 0 is consumed 1 is available and then 2 and so on. A very subtle thing, but quite clever!!!

提交回复
热议问题