Splitting a list into N parts of approximately equal length

前端 未结 30 1377
迷失自我
迷失自我 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 16:58

    This code is broken due to rounding errors. Do not use it!!!

    assert len(chunkIt([1,2,3], 10)) == 10  # fails
    

    Here's one that could work:

    def chunkIt(seq, num):
        avg = len(seq) / float(num)
        out = []
        last = 0.0
    
        while last < len(seq):
            out.append(seq[int(last):int(last + avg)])
            last += avg
    
        return out
    

    Testing:

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

提交回复
热议问题