繁体   English   中英

在 Python 中以表格格式打印

[英]Printing in table format in Python

例如,我有一个称为矩阵的二维 python 列表,下面给出了矩阵的行

['Adam', 57.6271186440678, 2.542372881355932, 0.0, 39.83050847457627]
['BAMON', 40.90909090909091, 9.090909090909092, 0.0, 50.0]
['BANESH', 72.61146496815287, 0.6369426751592356, 0.0, 26.751592356687897]
['BASA', 60.317460317460316, 4.761904761904762, 1.5873015873015872, 33.333333333333336]

我想将 2D 矩阵打印为带有标题(名称、高收入、亚洲中等收入、低收入、美国极端收入)的表格,并将考虑小数点后 2 位。

姓名 高收入 亚洲中等收入 低收入 美国的极端收入
亚当 57.62 2.54 0.0 39.83
巴蒙 40.90 9.09 0.0 50.0

如何在 python 中将其打印为表格或类似结构的表格。

matrix = [
    ['Adam', 57.6271186440678, 2.542372881355932, 0.0, 39.83050847457627],
    ['BAMON', 40.90909090909091, 9.090909090909092, 0.0, 50.0],
    ['BANESH', 72.61146496815287, 0.6369426751592356, 0.0, 26.751592356687897],
    ['BASA', 60.317460317460316, 4.761904761904762, 1.5873015873015872, 33.333333333333336],
]
col_names = ['High Income', 'Medium Income in Asia', 'Low Income', 'Extreme 
Income in America']

matrix.insert(0, col_names)

for e in matrix:
    if e == matrix[0]:
        print(f'{e[0]}\t\t{e[1]}\t\t{e[2]}\t\t{e[3]}')
    else:
        print(f'{e[0]}\t\t\t{round(e[1], 2)}\t\t\t\t\t\t{round(e[2], 
        2)}\t\t\t{round(e[3], 2)}')

我认为有更好的方法来格式化打印语句中的选项卡。

我使用这个 package https://pypi.org/project/prettytable/解决了这个问题

from prettytable import PrettyTable
table = PrettyTable()

table.field_names = ["Name", "Low Deviation in America", "Medium Income Percentage", "High Deviation in America", "Extreme Income"]
for row in matrix:
  if(len(row)>0):
    x.add_row(row)
print(x)

尝试这个:

(调整自https://www.delftstack.com/howto/python/data-in-table-format-python/

d = [['Adam', 57.6271186440678, 2.542372881355932, 0.0, 39.83050847457627],
['BAMON', 40.90909090909091, 9.090909090909092, 0.0, 50.0], 
['BANESH', 72.61146496815287, 0.6369426751592356, 0.0, 26.751592356687897],
['BASA', 60.317460317460316, 4.761904761904762, 1.5873015873015872, 33.333333333333336]]
     
print ("{:<8} {:<15} {:<15} {:<15} {:<15} ".format('Name', 'High Income', 'Medium Income in Asia', 'Low Income', 'Extreme Income in America'))

for v in d:
    name, high_income, medium_income, low_income, extreme_income = v
    print ("{:<8} {:<15} {:<15} {:<15} {:<15}".format( name, high_income, medium_income, low_income, extreme_income))

您可以通过调整花括号内的数字来指定列宽。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM