我该如何计算价格?

时间:2017-06-04 19:27:35

标签: python

menu_items = [
    [1, "Chicken Strips", 3.75], [2, "French Fries", 2.50],
    [3, "Hamburger", 4.00], [4, "Hot Dog", 3.50], [5, "Large Drink", 1.75],
    [6, "Medium Drink", 1.50], [7, "Milk Shake", 2.25], [8, "Salad", 4.25],
    [9, "Small Drink", 1.25] #<------- Order with price
]
print("Menu")
for item in menu_items:
    print('{} {} '.format(*item))

order = input('\n\nPlease enter the numbers of the items you would like: ')

print("You ordered: ", order)

for item in order:
    print(menu_items[int(item)-1])

我如何计算价格?进入后和输入时的总价格..谢谢

2 个答案:

答案 0 :(得分:1)

您可以在打印项目时获取价格并将它们添加到一起:

total = 0
for item in order:
    print(menu_items[int(item)-1])
    total += menu_items[int(item)-1][2]
print('Total price: {}'.format(total))

如果您想在订单后计算总数,可以使用以下列表推导:

order = input('\n\nPlease enter the numbers of the items you would like: ')
print("You ordered: ", order)
total = sum([menu_items[int(x)-1][2] for x in order]) #this line to calculate total

答案 1 :(得分:0)

首先,您需要拆分输入,以便人们可以输入1,2,3之类的内容。您可以使用split执行此操作(请确保使用in (read in sections under Python Membership Operators检查,。然后您只需要获取数组的最后一个元素并将其添加到总数中:

menu_items = [
    [1, "Chicken Strips", 3.75], [2, "French Fries", 2.50],
    [3, "Hamburger", 4.00], [4, "Hot Dog", 3.50], [5, "Large Drink", 1.75],
    [6, "Medium Drink", 1.50], [7, "Milk Shake", 2.25], [8, "Salad", 4.25],
    [9, "Small Drink", 1.25] #<------- Order with price
]
print("Menu")
for item in menu_items:
    print('{} {} '.format(*item))

order = input('\n\nPlease enter the numbers of the items you would like: ')
if ',' in order: #checks if , is in order
  order = order.split(",") #splits by ,
print("You ordered: ", order)
total = 0
for item in order:
    print(menu_items[int(item)-1])
    total = total + menu_items[int(item)-1][2] #adds 3rd element (price) to total (arrays are 0-indexed)
print("The total is $"+str(total)) #outputs total

阅读代码中的注释以获得更多说明。