Реализаций можно написать много.
Вариант 1: google "python split list into chunks"
Вариант 2: если в проекте используется numpy:
import numpy as np
def split(seq, num_chunks):
lst = np.array_split(np.array(seq), num_chunks)
return [x.tolist() for x in lst if len(x)]
Вариант 3 (только сейчас придумал, для py 2):
from __future__ import division
import math
def split(seq, num_chunks):
assert num_chunks
pos = 0
sz = len(seq)
result = []
while pos < sz:
num_items = int(math.ceil((sz - pos) / num_chunks))
result.append(seq[pos:pos + num_items])
pos = pos + num_items
num_chunks -= 1
return result
split([1, 2, 3, 4, 5, 6, 7, 8, 9], X)
# X
# 1 [[1, 2, 3, 4, 5, 6, 7, 8, 9]]
# 2 [[1, 2, 3, 4, 5], [6, 7, 8, 9]]
# 3 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# 4 [[1, 2, 3], [4, 5], [6, 7], [8, 9]]
# 5 [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
# 6 [[1, 2], [3, 4], [5, 6], [7], [8], [9]]
# 7 [[1, 2], [3, 4], [5], [6], [7], [8], [9]]
# 8 [[1, 2], [3], [4], [5], [6], [7], [8], [9]]
# 9 [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
# 10 [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
Вариант 4 - вариация варианта 3. Теперь split это генератор и всегда возвращает указанное кол-во частей/отрезков
def split(seq, num_chunks):
assert num_chunks
pos = 0
sz = len(seq)
while pos < sz:
num_items = int(math.ceil((sz - pos) / num_chunks))
yield seq[pos:pos + num_items]
pos = pos + num_items
num_chunks -= 1
for _ in range(num_chunks):
yield []
list(split([1, 2, 3, 4, 5, 6, 7, 8, 9], X))
# X
# ...
# 9 [[1], [2], [3], [4], [5], [6], [7], [8], [9]]
# 10 [[1], [2], [3], [4], [5], [6], [7], [8], [9], []]
# 11 [[1], [2], [3], [4], [5], [6], [7], [8], [9], [], []]
и т. д.