gpt4 book ai didi

python - 在数组中选择一个字符串变量 - Python

转载 作者:行者123 更新时间:2023-11-28 18:32:46 25 4
gpt4 key购买 nike

我正在努力从数组中挑选出一组字符串变量。

代码:

数组中的项:

pizzas_with_prices = [("Hawaiian", 8.5), ("Veg Deluxe", 8.5), ("Ham and Cheese", 8.5),("Super Supreme", 8.5), ("Seafood Deluxe", 8.5),("Meatlovers", 11.5), ("Hot 'n' Spicy", 11.5), ("BBQ Chicken and Bacon", 11.5),("Satay Chicken", 11.5)]

选择数组中的披萨:

for n in range(numPizza):
pizza = pizza + [int(input("Choose a pizza: "))]

所选披萨的总价:

for selected in pizza:
total_price += pizzas_with_prices[selected][1]
print("$%s" % (total_price))

我在获取数组中所选比萨饼的名称时遇到问题,但我可以获得所选比萨饼的总价格。感谢您的帮助!

编辑:

完整代码:

pizzas_with_prices = [("Hawaiian", 8.5), ("Veg Deluxe", 8.5), ("Ham and Cheese", 8.5),
("Super Supreme", 8.5), ("Seafood Deluxe", 8.5),
("Meatlovers", 11.5), ("Hot 'n' Spicy", 11.5), ("BBQ Chicken and Bacon", 11.5),
("Satay Chicken", 11.5)]

def menu():
print("Delivery or Pickup?")
print()
print("1] Delivery ($5 charge)")
print("2] Pickup")
print()

option = int(input(">>"))
if option < 1 or option > 2:
print("Only 1 or 2")
print()

if option == 1:
customerName = input("Enter customers name: ")
customerAddress = input("Enter customer Address: ")
customerPhone = input("Enter your phone number: ")
print()
print("Thank you", customerName, "Customers Address is", customerAddress, "and customers phone number is", customerPhone)
print()
orderPizza()

if option == 2:
customerName = input("Enter customers name: ")
print()
orderPizza()

def orderPizza():
numPizza=0
global pizzas_with_prices
Flag = True
while Flag:
try:
numPizza= int(input("How many Pizzas do you want? (MAX 7): "))
if numPizza ==0 or numPizza > 7:
print("Not a correct choice, Try again")
else:
Flag = False
except ValueError:
print("Not a number, Try again")

print()
for index, pizza in enumerate(pizzas_with_prices):
print("%d %s: $%s" % (index, pizza[0], pizza[1]))
pizza=[]

for n in range(numPizza): #covers values from 0 to 9
pizza = pizza + [int(input("Choose a pizza: "))]
print(pizza)
total_price = 0
for selected in pizza:
total_price += pizzas_with_prices[selected][1]
print("$%s" % (total_price))

menu()

最佳答案

IMO 最好使用字典来获取价格,这样您就不必遍历整个列表来获取价格。然后使用求和函数:

pizzas_with_prices = {'pizza1': 10, 'pizza2': 15}
selected_pizzas = []
# create the list of selected_pizzas with your code
# eg: selected_pizzas = ['pizza1', 'pizza2', 'pizza1']
pizza_price = sum(pizzas_with_prices[pizza] for pizza in pizza_list)

关于python - 在数组中选择一个字符串变量 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35308050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com