将列表格式化为表输出的列(python 3)

Jak*_*non 11 python formatting list columnsorting

我有一个循环收集的数据,并存储在只包含相同数据类型的单独列表中(例如,只包含字符串,只有浮点数),如下所示:

names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]
Run Code Online (Sandbox Code Playgroud)

我已将这些列表视为表的"列",并希望将它们打印为格式化的表,应该如下所示:

Names     | Weights | Costs | Unit_Costs  
----------|---------|-------|------------
bar       | 0.05    | 2.0   | 40.0
chocolate | 0.1     | 5.0   | 50.0
chips     | 0.25    | 3.0   | 12.0
Run Code Online (Sandbox Code Playgroud)

我只知道如何在表行中横向打印列表中的数据,我已经在线查看(以及在此站点上)以获得有关此问题的一些帮助,但是我只是设法找到帮助使它在python 2.7而不是3.5中工作.1这就是我正在使用的.
我的问题是:
如何从上面的4个列表中获取条目以打印到如上所示的表格中.

来自上面列表的每个项目索引是相关联的(即,来自4个列表的条目[0]与相同的项目相关联;条形,0.05,2.0,40.0).

Isr*_*man 7

这是一个实现基本python所需功能的小型实现(无特殊模块)。


names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]


titles = ['names', 'weights', 'costs', 'unit_costs']
data = [titles] + list(zip(names, weights, costs, unit_costs))

for i, d in enumerate(data):
    line = '|'.join(str(x).ljust(12) for x in d)
    print(line)
    if i == 0:
        print('-' * len(line))
Run Code Online (Sandbox Code Playgroud)

输出:


names       |weights     |costs       |unit_costs  
---------------------------------------------------
bar         |0.05        |2.0         |40.0        
chocolate   |0.1         |5.0         |50.0        
chips       |0.25        |3.0         |12.0        
Run Code Online (Sandbox Code Playgroud)


Rah*_*K P 7

一些有趣的表绘制texttable.

import texttable as tt
tab = tt.Texttable()
headings = ['Names','Weights','Costs','Unit_Costs']
tab.header(headings)
names = ['bar', 'chocolate', 'chips']
weights = [0.05, 0.1, 0.25]
costs = [2.0, 5.0, 3.0]
unit_costs = [40.0, 50.0, 12.0]

for row in zip(names,weights,costs,unit_costs):
    tab.add_row(row)

s = tab.draw()
print (s)
Run Code Online (Sandbox Code Playgroud)

结果

+-----------+---------+-------+------------+
|   Names   | Weights | Costs | Unit_Costs |
+===========+=========+=======+============+
| bar       | 0.050   | 2     | 40         |
+-----------+---------+-------+------------+
| chocolate | 0.100   | 5     | 50         |
+-----------+---------+-------+------------+
| chips     | 0.250   | 3     | 12         |
+-----------+---------+-------+------------+
Run Code Online (Sandbox Code Playgroud)

您可以texttable使用此命令进行安装pip install texttable.