python-small-examples

@author jackzhenguo
@desc
@tag yield generator
@version 
@date 2020/02/01

134 list分组(生成器版)

from math import ceil

def divide_iter(lst, n):
    if n <= 0:
        yield lst
        return
    i, div = 0, ceil(len(lst) / n)
    while i < n:
        yield lst[i * div: (i + 1) * div]
        i += 1

list(divide_iter([1, 2, 3, 4, 5], 0))  # [[1, 2, 3, 4, 5]]
list(divide_iter([1, 2, 3, 4, 5], 2))  # [[1, 2, 3], [4, 5]]
[上一个例子](/python-small-examples/md/133.html) [下一个例子](/python-small-examples/md/135.html)