将Python输出格式化为行

将Python输出格式化为行,python,Python,所以,我对编程还是有点陌生,我正在尝试用Python格式化一些数组的输出。我发现很难对格式化的某些方面进行思考。 我有几个数组要打印,格式是表格 headings = ["Name", "Age", "Favourite Colour"] names = ["Barry", "Eustace", "Clarence", "Razputin", "Harvey"] age = [39, 83, 90, 15, 23] favouriteColour = ["Green", "Baby Pink",

所以,我对编程还是有点陌生,我正在尝试用Python格式化一些数组的输出。我发现很难对格式化的某些方面进行思考。 我有几个数组要打印,格式是表格

headings = ["Name", "Age", "Favourite Colour"]
names = ["Barry", "Eustace", "Clarence", "Razputin", "Harvey"]
age = [39, 83, 90, 15, 23]
favouriteColour = ["Green", "Baby Pink", "Sky Blue", "Orange", "Crimson"]
我希望输出像这样:列宽略大于该列中的最大长度

Name          Age        Favourite Colour
Barry         39         Green
Eustace       83         Baby Pink
Clarence      90         Sky Blue
Razputin      15         Orange
Harvey        23         Crimson
我试着这样做:

mergeArr = [headings, name, age, favouriteColour]
但我认为这不会在正确的位置打印标题

我试过这个:

mergeArr = [name, age, favouriteColour] 
col_width = max(len(str(element)) for row in merge for element in row) + 2

for row in merge:
    print ("".join(str(element).ljust(col_width) for element in row))
但这会以列而不是行的形式打印每个对象的数据


谢谢你的帮助!谢谢。

你可以自己打印标题,包括姓名、年龄、喜欢的颜色

然后使用现有的代码,但是:

rows = zip(name, age, favouriteColour)
for row in rows...
您还可以查看表格软件包中格式良好的表格。

使用:


Jacob Krall使用zip组合列表是完全正确的。但是,一旦您完成了这项工作,如果您想让您的列很好地对齐(假设您使用的是Python3.x),那么请查看.format方法,该方法可用于字符串并作为Python打印函数的一部分。这允许您在输出中指定字段宽度。

只需添加额外的格式:

ll = [headings] + list(zip(names, age, favouriteColour))

for l in ll:
    print("{:<10}\t{:<2}\t{:<16}".format(*l))

# Name          Age Favourite Colour
# Barry         39  Green     
# Eustace       83  Baby Pink 
# Clarence      90  Sky Blue  
# Razputin      15  Orange    
# Harvey        23  Crimson  
我们使用列表前面的星号*来标记列表中的元素


第一个大括号表示字符串名称,其格式为:merge和Name在示例代码中均未定义谢谢!这很有效。你能给我解释一下花括号里的部分到底是做什么的吗?我有点理解,但不完全理解。我认为“\t”表示选项卡对吗?那么*是什么意思?
ll = [headings] + list(zip(names, age, favouriteColour))

for l in ll:
    print("{:<10}\t{:<2}\t{:<16}".format(*l))

# Name          Age Favourite Colour
# Barry         39  Green     
# Eustace       83  Baby Pink 
# Clarence      90  Sky Blue  
# Razputin      15  Orange    
# Harvey        23  Crimson  
headings = ["Name", "Age", "Favourite Colour"]
print("{:<10}\t{:<3}\t{:<16}".format(*headings))
# Name          Age Favourite Colour