我正在尝试打印一个列表,并且每5个索引将打印一行新行。例如,如果我有:
[1,2,3,4,5,6,7,8,9,10]
输出为:
1 2 3 4 5
6 7 8 9 10
到目前为止,我已经尝试过:
lst = [1,2,3,4,5,6,7,8,9,10]
for i in lst:
if len(lst) > 5:
print(lst,'\n')
但是我得到的是:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
.......
我该怎么办?
感谢您的帮助!
答案 0 :(得分:2)
在步骤中使用了for循环:
n_indices = 5
lst = [1,2,3,4,5,6,7,8,9,10]
for i in range(0, len(lst), n_indices):
print(lst[i:i+n_indices])
>>>[1, 2, 3, 4, 5]
>>>[6, 7, 8, 9, 10]
如果您想对格式感兴趣,可以使用print(*list[i:i+n_indices])
这样的参数解压缩并以以下格式获取输出:
1 2 3 4 5
6 7 8 9 10
答案 1 :(得分:2)
尝试一下:
a = [1,2,3,4,5,6,7,8,9,10]
for i in [a[c:c+5] for c in range(0,len(a),5) if c%5 == 0]:
print(*i)
输出将是:
1 2 3 4 5
6 7 8 9 10
您还可以将5
替换为任何其他数字或变量。
答案 2 :(得分:0)
比其他答案更惯用:
n = 5
lst = [1,2,3,4,5,6,7,8,9,10]
for group in zip(*[iter(lst)] * n):
print(*group)
1 2 3 4 5
6 7 8 9 10
对于更大的列表,它也更快:
In [1]: lst = range(1, 10001)
In [2]: n = 5
In [3]: %%timeit
...: for group in zip(*[iter(lst)] * n):
...: group
...:
236 µs ± 49.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [4]: %%timeit
...: for i in range(0, len(lst), n):
...: lst[i:i+n]
...:
1.32 ms ± 184 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
答案 3 :(得分:0)