允许用户使用索引位置从列表中进行选择



如果我没有问对这个问题,我先道歉,这是我第一次在这里问。

我有一个脚本,目前工作,但我正在努力改进它。

我创建了一个包含一周中的天数的字典,并允许用户根据每个值输入他们想在当天吃哪顿饭。但是,目前我要求用户从列表中输入他们选择的选项,这些选项必须完全匹配。例如"四川炒肉";这里很容易打错字。而不是管理错字,我想让它更容易使用,使他们的选择从列表中,例如,通过选择一个关键字从字典或从列表中的索引位置-我有麻烦,让这些工作虽然。

我的代码现在是这样的:

for d in week_meals:
try:
answer = input(f"What would you like to eat on {d}? options are {week_meals_list}")
week_meals_list.remove(answer)
week_meals[d] = answer
except ValueError:
print("That isn't an option!")
answer = input(f"What would you like to eat on {d}? options are {week_meals_list} type {week_meals_list.index")
week_meals_list.remove(answer)
week_meals[d] = answer

我尝试通过做下面的事情来创建一个字典,但我不知道如何设置每个项的键以递增1:

week_meals_dict = {}
for k in range(int(days)):
week_meals_dict[k] = None

,但我真的无法找到一种方法来遍历每个键,同时并行遍历列表。这可能吗?

这让我想到,让用户在列表中输入索引位置可能更容易,但我也不知道。

I figure out…

不太确定我完全理解为什么它工作,但这似乎:

for k in range(int(days)):
week_meals_dict[k] = week_meals_list[k]

我甚至可以把它清理一下但是我现在很满意

week_meals = {}
week_meals_list = ['meal1', 'meal2',]
for d in range(1, 8):
meal = None
while not meal:
answer = input(f"What would you like to eat on {d}? options are {week_meals_list}")
try:
meal = week_meals_list[int(answer)]
week_meals_list.remove(meal)
week_meals[d] = meal
except (IndexError, ValueError):
pass

首先,不要在迭代期间修改列表。

看来你是在试着为一周中的每一天搭配一顿饭。您可以按日期进行迭代:

week_meals_options = {1: "Chicken", 2: "Soup"} # Your dict containing choices mapped to the meal options
week_meals = {}
for day in week_days:
while True:
answer = input(f"What would you like to eat on {day}? options are {week_meals_options.keys()}")
if answer in week_meals_options:
week_meals[d] = week_meals_options.pop(answer) # Remove the option from the dict, and assign it to the day
break
else:
print("That isn't an option!")

相关内容

  • 没有找到相关文章

最新更新