使用输入的python列表

时间:2014-04-18 09:17:49

标签: python list input range

我正在为一个项目制作比萨饼订购系统,用户可以选择他们想要多少个比萨饼:

pizza_number=0
goodpizza_number=False 
while not goodpizza_number:
    try:
        pizza_number= int(input("How many Pizzas do you want? (MAX 5): "))
        if pizza_number ==0 or pizza_number > 5:
            print("Not a correct choice, Try again")
        else:
            goodpizza_number=True 
    except ValueError:
        print("Not a number, Try again")

然后有一个用户的比萨列表:

PIZZA_LIST=["Tandoori chicken: $8.50", "Prawn: $8.50", "Ham and cheese: $8.50", "Pepperoni: $8.50", "Hawaiian: $8.50","Beef and onion: $8.50","Meat lovers: $8.50", "Satay chicken: $13.50", "Apricot chicken: $13.50", "Supreme cheese:13.50", "Italian beef: $13.50", "Mediterraneo: $13.50"]
for index in range(0, len(PIZZA_LIST)):
    print(index, PIZZA_LIST[index])

用户可以选择他们想要的比萨:

pizza=[] 
for n in range(pizza_number): #covers values from 0 to 9 
    pizza = pizza + [int(input("Choose a pizza: "))] 
print(pizza) 

名单上的前7个比萨饼必须是8.50美元,而名单上的最后5个比萨饼必须是13.50美元。如何将用户的选择加在一起并获得他们选择的所有比萨饼的价格并增加总成本?

3 个答案:

答案 0 :(得分:0)

您需要在字典中创建另一个披萨名称和披萨价格。比萨的用户选择可以放在列表中。获得列表后,遍历列表以获取比萨饼名称价格dict的价格,然后添加以获得总价格。

答案 1 :(得分:0)

total_cost = sum([float(PIZZA_LIST[idx].split('$')[1]) for idx in pizza])

顺便说一下:你可以替换

pizza = pizza + [int(input("Choose a pizza: "))] 

pizza.append(int(input("Choose a pizza: ")))

答案 2 :(得分:0)

首先,您可能想要更改披萨名称和价格的呈现方式。由于您将用户输入作为整数,我建议使用元组列表:

pizzas_with_prices = [('Tandoori chicken', 8.5), ('Prawn', 8.5) ..., ('Mediterraneo', 13.5)]

然后你可以遍历你的pizza列表(可以更好地命名为selected_pizzas左右):

total_price = 0
for selected in selected_pizzas:
  total_price += pizzas_with_prices[selected][1]
print total_price

,一些改进代码的建议:

对于第一个代码块,您可以删除goodpizza_number

number_of_pizzas = 0
while 0 < number_of_pizzas <= 5:
  try:
    number_of_pizzas = int(input("How many Pizzas do you want? (MAX 5): "))
  except ValueError:
    print("Not a number, try again")

在第二个块上,按照建议,您可以使用元组列表并使用enumerate

pizzas_with_prices = [('Tandoori chicken', 8.5), ('Prawn', 8.5) ..., ('Mediterraneo', 13.5)]
for index, pizza in enumerate(pizzas_with_prices):
  print("%d %s: $%s" % (index, pizza[0], pizza[1]))