Splitting a list into N parts of approximately equal length

前端 未结 30 1819
迷失自我
迷失自我 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:04

    this code works for me (Python3-compatible):

    def chunkify(tab, num):
        return [tab[i*num: i*num+num] for i in range(len(tab)//num+(1 if len(tab)%num else 0))]
    

    example (for bytearray type, but it works for lists as well):

    b = bytearray(b'\x01\x02\x03\x04\x05\x06\x07\x08')
    >>> chunkify(b,3)
    [bytearray(b'\x01\x02\x03'), bytearray(b'\x04\x05\x06'), bytearray(b'\x07\x08')]
    >>> chunkify(b,4)
    [bytearray(b'\x01\x02\x03\x04'), bytearray(b'\x05\x06\x07\x08')]
    

提交回复
热议问题