Python 如何以网格格式打印列表列表?
如果我有一个列表,比如([1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15]) 如何在屏幕上以网格格式打印?就像:Python 如何以网格格式打印列表列表?,python,list,Python,List,如果我有一个列表,比如([1,2,3,4,5],[2,4,6,8,10],[3,6,9,12,15]) 如何在屏幕上以网格格式打印?就像: 1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 我的代码是 def print_table(listx): """returns a grid of a list of lists of numbers list of list -> grid""" for lists in listx:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
我的代码是
def print_table(listx):
"""returns a grid of a list of lists of numbers
list of list -> grid"""
for lists in listx:
for i in lists:
print(i,end='\t')
但我不知道如何像上面的例子那样将每个列表放在一行中。可能只是在主屏幕上添加一个空打印:
def print_table(listx):
"""returns a grid of a list of lists of numbers
list of list -> grid"""
for lists in listx:
for i in lists:
print(i,end='\t')
print()
如果图元的宽度变化大于制表符宽度,则可以使用固定宽度列(由空格填充):
>>对于列表x中的x:
... 对于x中的y:
... print(“{0:我的解决方案在行和\n
-分隔行中使用空格分隔的数字创建字符串。它使用方法和生成器表达式
str.center(宽度[,填充字符])
返回以长度-宽度字符串为中心。填充使用指定的fillchar(默认为ASCII空格)完成。原始
如果宽度小于或等于len,则返回字符串
输出:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
让我们把它分开:
str(i).center(5) for i in row
它迭代行,将值转换为字符串,并调用center
方法。结果是空格填充值
''.join(sequence_above)
它从值创建单个字符串。所以现在,字符串包含整行
'\n'.join(processed_row row in seq_of_rows)
它从上一步中获取处理过的行(字符串),并使用换行符将它们连接起来,因此结果是row1\nron2\nrow3
”。连接(i)
应该work@Udy同意使用“生产”代码,但可能这是一门介绍控制流和变量的课程,因此最好显示香肠是如何制作的。添加打印('\n')但当我运行它时,在我的最后一行中有一个“None”,就像第1行中的1、2、3、4、5等等。在最后一行,有一个“None”。为什么会出现这种情况?我在打印中添加了“\n”,它所做的只是在打印的数字之间添加一个空行,没有出现None。你是如何运行这段代码的?
''.join(sequence_above)
'\n'.join(processed_row row in seq_of_rows)