如何使用输入命令在列表中选择项目?



所以我试着做一个简单的糖果袋。其中一个选项是选择袋子里的糖果,另一个选项是随机选择袋子。随机袋子是有效的,但我如何根据用户的输入从列表中选择特定的糖果呢?

这就是我写那部分的方式。

os.system("cls")
customer_bag = []
candy_types = [["Sour strings", 2], ["Red Racecars", 2], ["Raspberry Boats", 1], ["Banana Skids", 3], ["Jungle Roar", 1], ["The Oh no Candy", 0,5]]
candy_types.sort()
for types in candy_types:
print(types)
print("nDo you want to choose candy or buy the shuffled candybag?")
candy_bag = int(input("1. Choose Candyn2. Shuffle!!!"))
if candy_bag == 1:
os.system("cls")
candy_choice = candy_bag[]
input()

elif candy_bag == 2:
os.system("cls")
print(random.choice(candy_types))
print(random.choice(candy_types))
print(random.choice(candy_types))
print(" ")
input("Press enter to return to Menu!")'''

在打印时添加项目编号。然后再执行一次input(),输入number of item。

import os
os.system("cls")
customer_bag = []
candy_types = [["Sour strings", 2], ["Red Racecars", 2], ["Raspberry Boats", 1], ["Banana Skids", 3], ["Jungle Roar", 1], ["The Oh no Candy", 0,5]]
candy_types.sort()
for i, types in enumerate(candy_types, start=1):
print(i, types)
print("nDo you want to choose candy or buy the shuffled candybag?")
candy_bag = int(input("1. Choose Candyn2. Shuffle!!!").strip())
if candy_bag == 1:
os.system("cls")
candy_choice = int(input("1. Choose Candy:"))
candy_bag = candy_types[candy_choice - 1][0]
print(candy_bag)

elif candy_bag == 2:
os.system("cls")
print(random.choice(candy_types))
print(random.choice(candy_types))
print(random.choice(candy_types))
print(" ")
input("Press enter to return to Menu!")