简体   繁体   English

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

[英]How to print every nth index of a python list on a new line?

I'm trying to print out a list and for every 5 indexes, it prints a new line. 我正在尝试打印一个列表,并且每5个索引将打印一行新行。 So for example, if I have: 因此,例如,如果我有:

  [1,2,3,4,5,6,7,8,9,10]

the output would be: 输出将是:

  1 2 3 4 5
  6 7 8 9 10

I tried this so far: 到目前为止,我已经尝试过了:

   lst = [1,2,3,4,5,6,7,8,9,10]

   for i in lst:
       if len(lst) > 5:
          print(lst,'\n')

but all I get is: 但我得到的是:

   [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] 

   .......

How could I do this? 我该怎么办?

Thanks for the help! 谢谢您的帮助!

Used a for loop with a step: 在步骤中使用了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]

If you want to be fancier with the formatting you can use argument unpacking like so: print(*list[i:i+n_indices]) and get outputs in this format: 如果您想使用这种格式,可以使用如下参数解包: print(*list[i:i+n_indices])并以这种格式获取输出:

1 2 3 4 5
6 7 8 9 10

Try this: 尝试这个:

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)

the output will be: 输出将是:

1 2 3 4 5
6 7 8 9 10

also you can replace 5 with any other number or variables. 您也可以用其他任何数字或变量替换5

A bit more idiomatic than the other answers: 比其他答案更惯用:

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

For larger lists, it's also much faster: 对于较大的列表,它也快得多:

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)

You Can use below code :- 您可以使用以下代码:-

for i in range(0,len(a),5):
    print(" ".join(map(str, a[i:i+5])))

It will give you desired output. 它将为您提供所需的输出。

代码片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM