Splitting a list into N parts of approximately equal length

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

    See more_itertools.divide:

    n = 2
    
    [list(x) for x in mit.divide(n, range(5, 11))]
    # [[5, 6, 7], [8, 9, 10]]
    
    [list(x) for x in mit.divide(n, range(5, 12))]
    # [[5, 6, 7, 8], [9, 10, 11]]
    

    Install via > pip install more_itertools.

提交回复
热议问题