Splitting a list into N parts of approximately equal length

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

    def chunk_array(array : List, n: int) -> List[List]:
        chunk_size = len(array) // n 
        chunks = []
        i = 0
        while i < len(array):
            # if less than chunk_size left add the remainder to last element
            if len(array) - (i + chunk_size + 1) < 0:
                chunks[-1].append(*array[i:i + chunk_size])
                break
            else:
                chunks.append(array[i:i + chunk_size])
                i += chunk_size
        return chunks
    

    here's my version (inspired from Max's)

提交回复
热议问题