简体   繁体   English

在 python 中打印时,在特定数量的输出后创建新行

[英]Make new line after a specific numbers of outputs while printing in python

Suppose there is a list;假设有一个列表; a = [1, 2, 3, 4, 5, 6, 7, 8, 9] a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, if I use print(*a), I'll get现在,如果我使用 print(*a),我会得到

1 2 3 4 5 6 7 8 9

But, I want to print it as;但是,我想将其打印为;

1 2 3
4 5 6
7 8 9

Here, the key point is making a new line after specific numbers of outputs , not after specific outputs .在这里,关键是在特定数量的输出之后换行,而不是在特定输出之后

Any built-in functions to achieve this?任何内置函数来实现这一点? If not, I'm open to hearing alternative ways.如果没有,我愿意听取其他方式。

You can use modulo operator with integer 3您可以将模运算符与 integer 3一起使用

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

for i in a:
    if i%3:
        print(i, end =" ")
    else:
        print(i)

if those integer members are quoted such as a=['1','2',"3",...] , then use casting to int as by replacing i%3 with int(i)%3如果引用了那些 integer 成员,例如a=['1','2',"3",...] ,则使用转换为int ,将i%3替换为int(i)%3

or the members are completely arbitrary string values such as a = ['1a', '4', "2p", ...] , then use and index( j ) for iterayion such as或者成员是完全任意的字符串值,例如a = ['1a', '4', "2p", ...] ,然后使用和 index( j ) 进行迭代,例如

j=0
for i in a:
    j+=1 
    if j%3:
        print(i, end =" ")
    else:
        print(i)

Your problem is a bit too special for there to be a general solution in the print function.您的问题有点太特殊了,无法在打印 function 中找到通用解决方案。 There is pprint for pretty-printing data structures, but as far as I can see even that does not have this option.有用于漂亮打印数据结构的pprint ,但据我所知,即使没有这个选项。

So this might be the shortest way.所以这可能是最短的方法。 The function takes n elements from the array and prints them each. function 从数组中取出 n 个元素并打印它们。

from math import ceil


def printN(n, array):
    for i in range(ceil(len(array) / n)):
        print(*array[i*n:(i+1)*n])

array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
printN(3, array)

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

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