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

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

    One word of advice for using zip this way. It will truncate your list if it's length is not evenly divisible. To work around this you could either use itertools.izip_longest if you can accept fill values. Or you could use something like this:

    def n_split(iterable, n):
        num_extra = len(iterable) % n
        zipped = zip(*[iter(iterable)] * n)
        return zipped if not num_extra else zipped + [iterable[-num_extra:], ]
    

    Usage:

    for ints in n_split(range(1,12), 3):
        print ', '.join([str(i) for i in ints])
    

    Prints:

    1, 2, 3
    4, 5, 6
    7, 8, 9
    10, 11
    

提交回复
热议问题