【问题标题】:Calculate from lists and print the output as table从列表计算并将输出打印为表格
【发布时间】:2020-01-05 16:51:27
【问题描述】:

我是 python 新手。

我有以下列表:

硬件 = [“主板”、“cpu”、“gpu”]

数量 = [5, 8, 4, 6]

成本 = [210.0, 250.5, 360.8]

我想打印一个输出,如您在下面链接中提供的 txt 文件中看到的那样。

我的尝试如下:

hardware = ["motherboard", "cpu", "gpu"]
amount = [5, 8, 4, 6]
cost   = [210.0, 250.5, 360.8]

product_cost = [a*b for a,b in zip(amount, cost)]
total = sum(product_cost)

titles = ['Hardware', 'Amount', 'Cost per item', 'Total cost per hardware']
data = [titles] + list(zip(hardware, amount, cost, product_cost))

for i, d in enumerate(data):
    line = ' '.join(str(x).ljust(12) for x in d)
    print(line)
    if i == 0:
        print(' ' * len(line))

print('\n' "Total cost: " + str(total))

但是我得到的输出不是你在 txt 文件中看到的期望的输出

我附上 txt 文件。这是txt的链接:

https://drive.google.com/open?id=1vANzMk9z2cxTWJRlwH3AkudN_jlG3iah

你能帮我得到想要的结果吗?

【问题讨论】:

  • 因为您的问题在于格式,您可以使用任何制作整齐表格的模块。但还是等一下,其他人可以帮忙。
  • 列有不同的宽度,所以首先你应该为列中的所有元素获取len(),并获取max()的长度。并且仅在第一列中使用ljust()。其他列需要rjust()。或为此查找模块 - 例如tabulate

标签: python list printing sum


【解决方案1】:

这应该符合您想要的结果。您可以根据需要自行调整表格中的间距。

hardware = ["motherboard", "cpu", "gpu"]
amount = [5, 8, 4, 6]
cost   = [210.0, 250.5, 360.8]

product_cost = [a*b for a,b in zip(amount, cost)]
total = sum(product_cost)

titles = ['Hardware', 'Amount', 'Cost per item', 'Total cost per hardware']
data = [titles] + list(zip(hardware, amount, cost, product_cost))

for i in range(len(data)):
    if i == 0:
      print('{:<15s}{:>10s}{:>20s}{:>30s}'.format(data[i][0],data[i][1],data[i][2],data[i][3]))
      print()
    else:
      print('{:<15s}{:>10d}{:>20.2f}{:>30.2f}'.format(data[i][0],data[i][1],data[i][2],data[i][3]))

print('\n' "Total cost: %.2f" % (total))

【讨论】:

    【解决方案2】:

    首先您必须将行转换为列并计算每列的最大长度

    rows = [titles] + list(zip(hardware, amount, cost, product_cost))
    
    columns = list(zip(*rows))
    
    lengths = [max([len(str(x)) for x in col]) for col in columns]
    

    接下来,您必须单独显示行中的每个元素,因为第一列需要 ljust 而其他列需要 rjust - 并且它们都需要与 lenghts 不同的值

    因为第一列中的文本比标题长,所以我在第二列中使用了额外的elif。让它更普遍需要更多的工作。

    hardware = ["motherboard", "cpu", "gpu"]
    amount = [5, 8, 4, 6]
    cost   = [210.0, 250.5, 360.8]
    product_cost = [a*b for a,b in zip(amount, cost)]
    
    total = sum(product_cost)
    
    titles = ['Hardware', 'Amount', 'Cost per item', 'Total cost per hardware']
    
    rows = [titles] + list(zip(hardware, amount, cost, product_cost))
    
    columns = list(zip(*rows))
    lengths = [max([len(str(x)) for x in col]) for col in columns]
    #print(lengths)
    
    for y, row in enumerate(rows):
        for x, item in enumerate(row): 
            l = lengths[x]
            if x == 0:
                print(str(item).ljust(l), end='')
            elif x == 1:
                print(str(item).rjust(l+2), end='')
            else:
                print(str(item).rjust(l+5), end='')
        print()
        if y == 0:
            print()
    
    print('\nTotal cost: {:.2f}'.format(total))
    

    结果

    Hardware     Amount     Cost per item     Total cost per hardware
    
    motherboard       5             210.0                      1050.0
    cpu               8             250.5                      2004.0
    gpu               4             360.8                      1443.2
    
    Total cost: 4497.20
    

    编辑:与模块tabulate类似

    hardware = ["motherboard", "cpu", "gpu"]
    amount = [5, 8, 4, 6]
    cost   = [210.0, 250.5, 360.8]
    product_cost = [a*b for a,b in zip(amount, cost)]
    total = sum(product_cost)
    
    titles = ['Hardware', 'Amount', 'Cost per item', 'Total cost per hardware']
    rows = list(zip(hardware, amount, cost, product_cost))
    
    import tabulate
    
    print(tabulate.tabulate(rows, headers=titles, floatfmt=".1f"))
    
    print('\nTotal cost: {:.2f}'.format(total))
    

    结果:

    Hardware       Amount    Cost per item    Total cost per hardware
    -----------  --------  ---------------  -------------------------
    motherboard         5            210.0                     1050.0
    cpu                 8            250.5                     2004.0
    gpu                 4            360.8                     1443.2
    
    Total cost: 4497.20
    

    【讨论】:

      猜你喜欢
      • 2015-11-06
      • 2012-03-21
      • 2019-09-19
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      相关资源
      最近更新 更多