我正在尝试通过组合来自两个列表的数据在 python 中构建一些可呈现的表格。
举个例子,假设我记录了比赛中的参赛者,并且我有每个人的姓名、时间和其他一些任意测量值:
headings = ['Name:','Time:','Awesomeness:']
info = [('Foo', 15.24242, 100), ('Bar', 421.333, 10), ('Pyth the Python', 3.333, 9000)]
我通过使函数 neatomatic9000 应用了一些格式,使表格的列正确缩进。
def neatomatic9000(something):
print("{0: <20}".format(something), end = '')
for i in headings:
neatomatic9000(i)
print('\n')
for j in info:
for k in j:
neatomatic9000(k)
print('\n')
我的表格是这样打印的:
Name: Time: Awesomeness:
Foo 15.24242 100
Bar 421.333 10
Pyth the Python 3.333 9000
这看起来不错,但我正在尝试将标题作为左侧的一列制作表格 - 本质上我正在尝试将其转置为如下所示:
Name: Foo Bar Pyth the Python
Time: 15.24242 421.333 3.333
Awesomeness: 100 10 9000
编辑:另一方面,令人愤怒的是,python 似乎缺少检查以查看某物是否为数字,无论它是 float 还是整数。我似乎无法合并一个条件来检查条目是否为数字,然后使用 "{:.2f}".format(k)
请您参考如下方法:
你的意思是这样的吗?
for num, heading in enumerate(headings):
neatomatic9000(heading)
for j in info:
neatomatic9000(j[num])
print('\n')
输出:
Name: Foo Bar Pyth the Python
Time: 15.24242 421.333 3.333
Awesomeness: 100 10 9000
enumerate 函数将像 [a, b, c] 这样的列表变成像 [(0, a), (1, b), (2, c)]。我们希望每个标题一行,所以这是我们的外循环。然后对于第 0 个标题,我们为每个参赛者打印第 0 个值。对于下一个标题,我们打印每个参赛者的下一个值,依此类推。
请注意,这基本上是您的循环,但由内而外。
