带有列标题的Python打印列表

时间:2017-03-12 22:29:35

标签: list

所以我有一个包含这些值的嵌套列表

#[[Mark, 10, Orange],
#[Fred, 15, Red],
#[Gary, 12, Blue],
#[Ned, 21, Yellow]]

您可以看到文件已布局,因此您拥有(姓名,年龄,favcolour) 我想这样做,所以我可以显示每个列及其相应的标题 E.G

Name|Age|Favourite colour
Mark|10 |Orange
Fred|15 |Red
Gary|12 |Blue
Ned |21 |Yellow

谢谢!

1 个答案:

答案 0 :(得分:0)

使用str.format()函数的简单解决方案:

l = [['Mark', 10, 'Orange'],['Fred', 15, 'Red'],['Gary', 12, 'Blue'],['Ned', 21, 'Yellow']]
f = '{:<10}|{:<3}|{:<15}'   # format

# header(`Name` column has some gap as there could be long names, like "Cristopher")
print('Name      |Age|Favourite colour') 

for i in l:
    print(f.format(*i))

输出:

Name      |Age|Favourite colour
Mark      |10 |Orange         
Fred      |15 |Red            
Gary      |12 |Blue           
Ned       |21 |Yellow