Splitting a list into N parts of approximately equal length

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

    This is the raison d'être for numpy.array_split*:

    >>> import numpy as np
    >>> print(*np.array_split(range(10), 3))
    [0 1 2 3] [4 5 6] [7 8 9]
    >>> print(*np.array_split(range(10), 4))
    [0 1 2] [3 4 5] [6 7] [8 9]
    >>> print(*np.array_split(range(10), 5))
    [0 1] [2 3] [4 5] [6 7] [8 9]
    

    *credit to Zero Piraeus in room 6

提交回复
热议问题