格式化在python代码下无法正确进行

时间:2018-09-07 15:23:20

标签: python

我有一个代码,要求订购果汁和苹果酒的人数,并据此计算总数,小计,平均值等。我在格式方面遇到问题,例如标题以下(例如:名称,苹果酒,小计),数字不能正确反映在相应标题下。如何在python中格式化

How many people ordered? 2
Enter the name of Person #1: Richard
How many orders of cider did Richard have? 13
How many orders of juice did Richard have? 9
Enter the name of Person #2: George
How many orders of cider did George have? 7
How many orders of juice did George have? 21


Names   Cider   Juice     Subtotal (Cider)   Subtotal (Juice)   Total
--------------------------------------------------------------------------------
Richard 13   9 $ 71.50 $ 40.50 $ 112.00
George   7    21 $ 38.50 $ 94.50 $ 133.00

--------------------------------------------------------------------------------
Total 20 30 $ 231.00 $ 261.00 $ 492.00
Average 10.50 14.50 $ 57.75 $ 65.25 $ 123.00

代码:

print("This program calculates the prices of the orders")
person=int(input("How many people ordered?"))


person_names=[]
cider_order=[]
juice_order=[]
cider__subtotal_orders=[]
juice__subtotal_orders=[]
total_orders=[]

for a in range(person):
    personnames=input("Enter the name of Person #%d:"%(a+1))
    person_names.append(personnames)
    cider=int(input("How many orders of cider did %s have?"%personnames))
    cider_order.append(cider)
    juice=int(input("How many orders of juice did %s have?"%personnames))
    juice_order.append(juice)
    cider__subtotal_orders.append(cider*5.50)
    juice__subtotal_orders.append(juice*4.50)
    total_orders.append(cider__subtotal_orders[a]+juice__subtotal_orders[a])

    print("\n\n")

print("Name     Cider Juice Subtotal (Cider) Subtotal (Juice) Total")
print("-------------------------------------------------------------")
for a in range(person):
    print(person_names[a],cider_order[a],juice_order[a],"$",cider__subtotal_orders[a],"$",juice__subtotal_orders[a],"$",total_orders[a])
print("-------------------------------------------------------------")

print("total",sum(cider_order),sum(juice_order),"$",sum(cider__subtotal_orders),"$",sum(juice__subtotal_orders),"$",sum(total_orders))
print("Average",sum(cider_order)/person,sum(juice_order)/person,"$",sum(cider__subtotal_orders)/person,"$",sum(juice__subtotal_orders)/person,"$",
      sum(total_orders)/person)

1 个答案:

答案 0 :(得分:0)

这也许可以帮助您

 a=['Names','Cider','Juice','Subtotal(Cider)','Subtotal(Juice)', 'Total']
 b=['Richard','13','9','$ 71.50','$ 40.50','$ 112.00']
 for i in range(len(b)):
      maxi=max(len(a[i]),len(b[i]))
      a[i]=a[i].center(maxi)
      b[i]=b[i].center(maxi)

 title=' '.join(a)
 data=' '.join(b)
 line='-'*len(title)
 print(title,line,data,sep='\n')

 Names  Cider Juice Subtotal(Cider) Subtotal(Juice)  Total  
------------------------------------------------------------
 Richard   13    9       $ 71.50         $ 40.50     $ 112.00