云栖问答

找不到答案?去提问题

python 索引 2019-01-23 13:42:40

如何在新行上打印python列表的每个第n个索引?

我正在尝试打印出一个列表,并且对于每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]

.......
我怎么能这样做?

2个回答

0

python小能手

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)

0

python小能手

使用带有步骤的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
GO