Мне кажется, у меня есть более короткий ответ, который не требует импорта каких-либо библиотек.
Вот вам одна строчка:
>>> lst = list(range(60))
>>> [lst[i * 16: (i + 1) * 16] for i in range(len(lst) / size + int((len(lst) % 16) > 0)))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31], [32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47], [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]
Теперь как функция (предполагается, что вы работаете со списком):
def partition(lst, size):
assert(size >= 0)
if not lst: return ()
return (lst[i * size: (i + 1) * size] for i in range(len(lst) / size + int((len(lst) % size) > 0)))
>>> partition(list(range(78)), 17)
<generator object <genexpr> at 0x7f284e33d5a0>
>>> list(partition(list(range(78)), 17))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33], [34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67], [68, 69, 70, 71, 72, 73, 74, 75, 76, 77]]
>>> list(partition(range(16), 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
>>> print list(partition(range(0), 4))
[]
РЕДАКТИРОВАНИЕ: Новое решение, основанное на ответе Триптиха:
def partition(lst, size):
assert(size >= 0)
if not lst: return ()
return (lst[i: i + size] for i in range(0, len(lst), size))
>>> partition(list(range(78)), 17)
<generator object <genexpr> at 0x025F5A58>
>>> list(partition(list(range(78)), 17))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33], [34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50], [51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67], [68, 69, 70, 71, 72, 73, 74, 75, 76, 77]]
>>> list(partition(list(range(16)), 17))
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]
>>> list(partition(list(range(16)), 4))
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
>>> list(partition([], 17))
[]
>>>