如何从列表中打印大小为5的块,以及不具有块大小为5的其余尾端
例如
a = list(range(23))
我要打印出
[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19], [20,21,22]
答案 0 :(得分:5)
from functools import partial
from itertools import islice
def take(n, iterable):
return tuple(islice(iterable, n))
def chunked(iterable, n):
return iter(partial(take, n, iter(iterable)), tuple())
a = list(range(23))
print(list(chunked(a, 5)))
# [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9), (10, 11, 12, 13, 14),
# (15, 16, 17, 18, 19), (20, 21, 22)]
或简单地:
n = 5
[a[j:j+n] for j in range(0, len(a), n)]