Splitting a list into N parts of approximately equal length

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

    Here is my solution:

    def chunks(l, amount):
        if amount < 1:
            raise ValueError('amount must be positive integer')
        chunk_len = len(l) // amount
        leap_parts = len(l) % amount
        remainder = amount // 2  # make it symmetrical
        i = 0
        while i < len(l):
            remainder += leap_parts
            end_index = i + chunk_len
            if remainder >= amount:
                remainder -= amount
                end_index += 1
            yield l[i:end_index]
            i = end_index
    

    Produces

        >>> list(chunks([1, 2, 3, 4, 5, 6, 7], 3))
        [[1, 2], [3, 4, 5], [6, 7]]
    

提交回复
热议问题