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

后端 未结 6 1442
渐次进展
渐次进展 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:14

    iter(s) returns an iterator for s.

    [iter(s)]*n makes a list of n times the same iterator for s.

    So, when doing zip(*[iter(s)]*n), it extracts an item from all the three iterators from the list in order. Since all the iterators are the same object, it just groups the list in chunks of n.

提交回复
热议问题