将一个列表分成n个大小的块是一个standard recipe on the itertools page,称为grouper
from itertools import *
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
这将按如下方式工作:
test_data = list(range(13,91))
test_output = list(grouper(test_data, 5))
print (test_output)
[(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), (78, 79, 80, 81, 82), (83, 84, 85, 86, 87), (88, 89, 90, None, None)]
这给出了五人组的元组而不是列表,但这应该适用于大多数目的。
一种可能更容易理解的方法就是在 5 秒内遍历列表并每次收集一个 5 长的切片。
test_output = [test_data[a:a+5] for a in range(0,len(test_data),5)]
print(test_output)
[[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], [78, 79, 80, 81, 82], [83, 84, 85, 86, 87], [88, 89, 90]]
编辑:在我看来,您实际上可能希望将列表打印为 5 字段表。为了应对可能较短的最后一行,我会将列表的各个部分放入一个简短的工作列表中:
for a in range(0,len(test_data),5):
pr_data = test_data[a:a+5]
print(("{:>8}"*len(pr_data)).format(*pr_data))
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
78 79 80 81 82
83 84 85 86 87
88 89 90
这里我在格式字符串中指定了一个字段宽度为 8。