Splitting a list into N parts of approximately equal length

前端 未结 30 1619
迷失自我
迷失自我 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 17:05

    def evenly(l, n):
        len_ = len(l)
        split_size = len_ // n
        split_size = n if not split_size else split_size
        offsets = [i for i in range(0, len_, split_size)]
        return [l[offset:offset + split_size] for offset in offsets]
    

    Example:

    l = [a for a in range(97)] should be consist of 10 parts, each have 9 elements except the last one.

    Output:

    [[0, 1, 2, 3, 4, 5, 6, 7, 8],
     [9, 10, 11, 12, 13, 14, 15, 16, 17],
     [18, 19, 20, 21, 22, 23, 24, 25, 26],
     [27, 28, 29, 30, 31, 32, 33, 34, 35],
     [36, 37, 38, 39, 40, 41, 42, 43, 44],
     [45, 46, 47, 48, 49, 50, 51, 52, 53],
     [54, 55, 56, 57, 58, 59, 60, 61, 62],
     [63, 64, 65, 66, 67, 68, 69, 70, 71],
     [72, 73, 74, 75, 76, 77, 78, 79, 80],
     [81, 82, 83, 84, 85, 86, 87, 88, 89],
     [90, 91, 92, 93, 94, 95, 96]]
    

提交回复
热议问题