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

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

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]

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

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

我只知道如何在表格行中水平打印列表中的数据,我已经在网上(和本网站)查看了有关此问题的一些帮助,但是我只设法找到了让它在 python 2.7 中工作的帮助而不是我正在使用的 3.5.1。
我的问题是:
如何从上述 4 个列表中获取条目以打印到如上所示的表格中。

以上列表中的每个项目索引都是相关联的(即 4 个列表中的 entry[0] 与同一项目相关联;bar, 0.05, 2.0, 40.0)。

最佳答案

这是一个小实现,可以在基本 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))

输出:


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        

https://stackoverflow.com/questions/39032720/

相关文章:

javascript - 从字符串,javascript 中获取 x 像素值文本的最可靠方法

java - Eclipse 格式化程序 : can it ignore annotations?

c++ - clang-format:总是打破所有参数,每行一个

visual-studio - Visual Studio 格式化 - 更改方法颜色

c# - 日期时间格式,如 HH :mm 24 Hours without AM/PM

c# - 如何拆分保留整个单词的字符串?

algorithm - 如何有效地为特定宽度的字符串找到理想的列数?

SQL Server 2005 For XML Explicit - 需要帮助格式化

php - 在 PHP 中从 SQL 格式化时间戳的最简单方法是什么?

java - 任何可用于 java 文件的命令行格式工具?