Splitting a list into N parts of approximately equal length

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

    As long as you don't want anything silly like continuous chunks:

    >>> def chunkify(lst,n):
    ...     return [lst[i::n] for i in xrange(n)]
    ... 
    >>> chunkify(range(13), 3)
    [[0, 3, 6, 9, 12], [1, 4, 7, 10], [2, 5, 8, 11]]
    

提交回复
热议问题