Splitting a list into N parts of approximately equal length

前端 未结 30 1628
迷失自我
迷失自我 2020-11-22 16:16

What is the best way to divide a list into roughly equal parts? For example, if the list has 7 elements and is split it into 2 parts, we want to get 3 elements in o

30条回答
  •  执笔经年
    2020-11-22 17:03

    This one provides chunks of length <= n, >= 0

    def

     chunkify(lst, n):
        num_chunks = int(math.ceil(len(lst) / float(n))) if n < len(lst) else 1
        return [lst[n*i:n*(i+1)] for i in range(num_chunks)]
    

    for example

    >>> chunkify(range(11), 3)
    [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
    >>> chunkify(range(11), 8)
    [[0, 1, 2, 3, 4, 5, 6, 7], [8, 9, 10]]
    

提交回复
热议问题