如何将此输出转换为选项卡

2024-04-24 20:11:27 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的输出,也是我打印格式化表的尝试,但是它不断给出错误“格式中的零长度字段名”。 如何将输出打印为格式化表而不使用模块,最好使用以下/类似方法:

这些名字是为了测试而编的:)

代码


Tags: 模块方法代码格式错误名字字段名
1条回答
网友
1楼 · 发布于 2024-04-24 20:11:27
newOrder = [['gtin', 'name', 'price', 'quantity'], ['01234567', 'apples', '1.50', '12', ],
            ['01234566', 'applesxyz', '1.50', '12', ], ['01234565', 'asdasdapples', '1.50', '102', ],
            ['11234567', 'apples', '1.50', '12', ]]

widths = [max(len(row[i]) for row in newOrder) for i in range(len(newOrder[0]))]

for row in newOrder:
    print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))

输出:

gtin     | name         | price | quantity
01234567 | apples       | 1.50  | 12      
01234566 | applesxyz    | 1.50  | 12      
01234565 | asdasdapples | 1.50  | 102     
11234567 | apples       | 1.50  | 12  

这是基于我的答案here。我不想把它标记为重复,因为这个问题不涉及CSV

相关问题 更多 >