Splitting a list into N parts of approximately equal length

前端 未结 30 1625
迷失自我
迷失自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 16:45

    This will do the split by a single expression:

    >>> myList = range(18)
    >>> parts = 5
    >>> [myList[(i*len(myList))//parts:((i+1)*len(myList))//parts] for i in range(parts)]
    [[0, 1, 2], [3, 4, 5, 6], [7, 8, 9], [10, 11, 12, 13], [14, 15, 16, 17]]
    

    The list in this example has the size 18 and is divided into 5 parts. The size of the parts differs in no more than one element.

提交回复
热议问题