Python:将列表的列表打印为表格 [英] Python : Print list of list as tables
问题描述
我是python的新手,正在遇到问题.我有一个文本文件,我读入一个列表,然后将其分成大块或团队".子列表的数量是根据我想要的团队数量创建的.所有这一切都完成了.但我想以一种很好的表格格式将其打印出来. Ive调查了以下问题此,这,但是我不是我要找的东西.我什至查看了pypi模块PrettyTable和DataGrid.
I am new to python and was going through a problem. I have a text file which I read into a list and then divide it into chunks or "teams". The number of sub lists are created based on the number of teams I want. All this is done. But I want to print it out in a nice tabular format. Ive looked into the following questions this, this and this, but they are not what I ma looking for. Ive even looked at pypi modules PrettyTable and DataGrid.
我的最终列表如下:
['name9', 'name2'], ['name4', 'name11'], ['name10', 'name3'], ['name7', 'name6'], ['name5', 'name8'], ['name']]
我这样打印出来:
for i in range(len(l)):
print "Teams{}\t\t ".format(i+1),
print
for x in itertools.izip_longest(*l, fillvalue="."):
print "\n"
t = "\t\t ".join(str(i) for i in x)
print t
这将导致:
Teams1 Teams2 Teams3 Teams4 Teams5 Teams6
name9 name4 name10 name7 name5 name
name2 name11 name3 name6 name8 .
有什么办法可以得到这样的输出:
Is there any way I can get an output like this:
Team 1 Team 2 Team 3 Team 4 Team 5 Team 6
-------------------------------------------------------------------
name9 name4 name10 name7 name5 name
name2 name11 name3 name6 name8 .
然后正确对齐它们?
推荐答案
使用 prettytable
from prettytable import PrettyTable
teams = ['team%d'%(x+1) for x in range(len(l)) ]
x = PrettyTable(teams)
for i in itertools.izip_longest(*l, fillvalue="."):
x.add_row(i)
x.vertical_char = ' '
x.junction_char = '-'
print(x)
---------------------------------------------------
team1 team2 team3 team4 team5 team6
---------------------------------------------------
name9 name4 name10 name7 name5 name
name2 name11 name3 name6 name8 .
---------------------------------------------------
lines = x.get_string().split('\n')
output = '\n'.join(lines[1:-1])
print(output)
team1 team2 team3 team4 team5 team6
---------------------------------------------------
name9 name4 name10 name7 name5 name
name2 name11 name3 name6 name8 .
这篇关于Python:将列表的列表打印为表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!