Splitting a list into N parts of approximately equal length

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

    The same as job's answer, but takes into account lists with size smaller than the number of chuncks.

    def chunkify(lst,n):
        [ lst[i::n] for i in xrange(n if n < len(lst) else len(lst)) ]
    

    if n (number of chunks) is 7 and lst (the list to divide) is [1, 2, 3] the chunks are [[0], [1], [2]] instead of [[0], [1], [2], [], [], [], []]

提交回复
热议问题