Python超市结合了列表和格式

时间:2014-11-29 02:49:08

标签: python

我必须创建一个程序,要求用户输入要购买的商品数量。程序然后要求用户输入每个项目和价格,给出总数并提供更改量。

我被困在需要合并列表并以货币格式输出项目和成本的部分

#Checkout program

print "Welcome to the checkout counter! How many items will you be purchasing?"
number = int (raw_input ())

grocerylist = []
costs = []
for i in range(number):
    groceryitem = raw_input ("Please enter the name of product %s:" % (i+1))
    grocerylist.append(groceryitem)
    itemcost = float(raw_input ("What is the cost of %s ?" % groceryitem))
    costs.append(itemcost)

order = {}

for index in range (min(len(grocerylist), len(costs))):
    order[grocerylist[index]] = costs[index]
print ("This is your purchase") + str(order)

3 个答案:

答案 0 :(得分:0)

你可以直接将它存储在字典中:

#Checkout program

print "Welcome to the checkout counter! How many items will you be purchasing?"
number = int(raw_input ())
order = {}
for i in range(number):
    groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
    itemcost = float(raw_input("What is the cost of %s ?" % groceryitem))
    order[groceryitem] = itemcost

print("your Purchase")
for x,y in order.items():
     print (str(x), "$"+str(y))

注意:order.values()会给你价目表       order.keys()会给你项目清单
在这里阅读字典:Dictionary

演示:

>>> order = {'cake':100.00,'Coke':15.00}
>>> for x,y in order.items():
...     print(x,"$"+str(y))
... 
cake $100.0
Coke $15.0

更好地使用format

>>> for x,y in enumerate(order.items()):
...     print("Item {}: {:<10} Cost ${:.2f}".format(x+1,y[0],y[1]))
... 
Item 1: cake       Cost $100.00
Item 2: Coke       Cost $15.00

将其制成表格:

print("{:<5}{:<10}{}".format("Num","Item","Cost"))
for x,y in enumerate(order.items()):
    print("{:<5}{:<10}${:.2f}".format(x+1,y[0],y[1]))
print("{:>10}{:>6}{:.2f}".format("Total","$",sum(order.values())))

Num  Item      Cost
1    cake      $100.00
2    Coke      $15.00
     Total     $115.00

答案 1 :(得分:0)

# the simple way
for index in range (min(len(grocerylist), len(costs))):
    print("Item: %s  Cost: $%5.2f " % (grocerylist[index], costs[index]))

或者您可以使用locale currency()函数..请参阅Currency formatting in Pythonhttps://docs.python.org/2/library/locale.html

答案 2 :(得分:0)

除了上述方法之外,您还可以迭代order.keys()。并使用内置的字符串方法进行格式化。这是一个例子。

>>> order = {1 : 10.23, 2 : 1.0, 3 : 3.99}
>>> for key, val in order.items():
...     print "Item " + key + ": ", "$" + "{0:.2f}".format(val)
... 
Item 1: $10.23
Item 2: $1.00
Item 3: $3.99