如何在新行上打印python列表的第n个索引? [英] How to print every nth index of a python list on a new line?

查看:37
本文介绍了如何在新行上打印python列表的第n个索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印一个列表,对于每 5 个索引,它打印一个新行.例如,如果我有:

I'm trying to print out a list and for every 5 indexes, it prints a new line. So for example, if I have:

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

输出为:

  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')

但我得到的只是:

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

   .......

我该怎么办?

感谢您的帮助!

推荐答案

尝试一下:

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 替换为其他任何数字或变量.

also you can replace 5 with any other number or variables.

这篇关于如何在新行上打印python列表的第n个索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆