Splitting a list into N parts of approximately equal length

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

    I tried most part of solutions, but they didn't work for my case, so I make a new function that work for most of cases and for any type of array:

    import math
    
    def chunkIt(seq, num):
        seqLen = len(seq)
        total_chunks = math.ceil(seqLen / num)
        items_per_chunk = num
        out = []
        last = 0
    
        while last < seqLen:
            out.append(seq[last:(last + items_per_chunk)])
            last += items_per_chunk
    
        return out
    

提交回复
热议问题