例如,我有一个名为matrix的2D python列表,marix的行在下面
['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位数字。
名称 | 高收入 | 亚洲中等收入美国低收入端收入|||
---|---|---|---|---|
Adam | 57.62 | 2.54 | 0.0 | 39.83 |
Bamon | 40.90 | 9.09 | 0.0 | 50.0 |
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]}tt{e[1]}tt{e[2]}tt{e[3]}')
else:
print(f'{e[0]}ttt{round(e[1], 2)}tttttt{round(e[2],
2)}ttt{round(e[3], 2)}')
我认为有一种更好的方法来格式化打印报表中的选项卡。
我用这个包解决了这个问题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))
可以通过调整大括号内的数字来指定列宽。
希望这能有所帮助。