【问题标题】:Using nested "for" loops to produce results in a formatted table in Python在 Python 中使用嵌套的“for”循环在格式化表中生成结果
【发布时间】:2017-04-08 11:46:45
【问题描述】:

我想知道是否有人可以帮助我编写一个程序来计算正常定价的商品的销售价格 从 9.95 美元到 49.95 美元,销售价格可以享受 5% 到 50% 的折扣。展示 结果以适当格式的表格显示。

我已经做到了

price = [9.95, 14.95, 19.95, 24.95, 29.95, 34.95, 39.95, 44.95, 49.95]
discount = range(5, 51, 5)
for i in discount:
    K = 1 - (i/100)
    for j in price:
        P = j * K
        V ="{:.2f}".format(P)
        C ='{:>7}'.format(V)
        print(C, end=" ")
    print()

给了

    9.45   14.20   18.95   23.70   28.45   33.20   37.95   42.70   47.45 
    8.96   13.46   17.95   22.45   26.95   31.46   35.96   40.46   44.96 
    8.46   12.71   16.96   21.21   25.46   29.71   33.96   38.21   42.46 
    7.96   11.96   15.96   19.96   23.96   27.96   31.96   35.96   39.96 
    7.46   11.21   14.96   18.71   22.46   26.21   29.96   33.71   37.46 
    6.96   10.46   13.96   17.46   20.96   24.46   27.96   31.46   34.96 
    6.47    9.72   12.97   16.22   19.47   22.72   25.97   29.22   32.47 
    5.97    8.97   11.97   14.97   17.97   20.97   23.97   26.97   29.97 
    5.47    8.22   10.97   13.72   16.47   19.22   21.97   24.72   27.47 
    4.97    7.47    9.97   12.47   14.97   17.48   19.98   22.48   24.98 

但我需要它看起来像这样

Normal p ri c e :    $9 . 9 5  $14 . 9 5  $19 . 9 5  $24 . 9 5  $29 . 9 5  $34 . 9 5  $39 . 9 5  $44 . 9 5  $49 . 9 5
         %o f f : 5%  9 . 4 5  1 4 . 2 0  1 8 . 9 5  2 3 . 7 0  2 8 . 4 5  3 3 . 2 0  3 7 . 9 5  4 2 . 7 0  4 7 . 4 5
         %o f f : 10%  8 . 9 6  1 3 . 4 6  1 7 . 9 5  2 2 . 4 5  2 6 . 9 5  3 1 . 4 6  3 5 . 9 6  4 0 . 4 6  4 4 . 9 6

【问题讨论】:

    标签: python python-3.x for-loop


    【解决方案1】:

    我会使用带有 print 的内联 if 语句来前置标记它的列:

    price = [9.95, 14.95, 19.95, 24.95, 29.95, 34.95, 39.95, 44.95, 49.95]
    discount = range(0, 51, 5)
    for i in discount:
        K = 1 - (i/100)
        for j in price:
            P = j * K
            V ="${:.2f}".format(P)
            C ='{:>7}'.format(V)
            print("o f f : " +str(i) + "%" if i else "Normal P r i c e : " if j else "", str(C).replace("."," . "), end=" ")
        print()
    

    【讨论】:

      【解决方案2】:

      你可以使用下面的sn-p

      price = [9.95, 14.95, 19.95, 24.95, 29.95, 34.95, 39.95, 44.95, 49.95]
      discount = range(5, 51, 5)
      row_format = "{:>15}" * (len(price) + 1)
      print(row_format.format("Normal price:", *price))
      for d in discount:
          K = 1 - (float(d)/100)
          prices_adj = [p*K for p in price]
          print(row_format.format("{} %  off:".format(d), *prices_adj))
      

      或者查看一些包,例如 PrettyTabletabulatetexttable

      【讨论】:

        猜你喜欢
        • 2022-12-13
        • 1970-01-01
        • 2021-07-07
        • 1970-01-01
        • 1970-01-01
        • 2015-06-26
        • 1970-01-01
        • 2013-03-17
        • 1970-01-01
        相关资源
        最近更新 更多