Splitting a list into N parts of approximately equal length

前端 未结 30 1758
迷失自我
迷失自我 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's another variant that spreads the "remaining" elements evenly among all the chunks, one at a time until there are none left. In this implementation, the larger chunks occur at the beginning the process.

    def chunks(l, k):
      """ Yield k successive chunks from l."""
      if k < 1:
        yield []
        raise StopIteration
      n = len(l)
      avg = n/k
      remainders = n % k
      start, end = 0, avg
      while start < n:
        if remainders > 0:
          end = end + 1
          remainders = remainders - 1
        yield l[start:end]
        start, end = end, end+avg
    

    For example, generate 4 chunks from a list of 14 elements:

    >>> list(chunks(range(14), 4))
    [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10], [11, 12, 13]]
    >>> map(len, list(chunks(range(14), 4)))
    [4, 4, 3, 3]
    

提交回复
热议问题