【问题标题】:Allowing user to select from a list using the index location允许用户使用索引位置从列表中进行选择
【发布时间】:2021-09-04 12:45:41
【问题描述】:

如果我没有正确地问这个问题,我很抱歉,这是我第一次在这里问。

我有一个当前可以运行的脚本,但我正在努力改进它。

我创建了一个星期几的字典,并根据每个值允许用户输入他们想在那天吃哪顿饭。但是,目前我要求用户从列表中键入他们选择的选项,该选项必须完全匹配。例如“四川炒猪肉”——这里很容易打错。而不是管理错字,我想让用户更容易从列表中进行选择,例如通过从字典中选择一个键或从列表中选择一个索引位置 - 我无法让其中任何一个工作。

我的代码现在看起来像这样:

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

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

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

【问题讨论】:

    标签: python list dictionary input


    【解决方案1】:

    我想通了……

    不太确定我是否完全理解它的工作原理,但这似乎是:

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

    我什至可以把它清理干净,但我现在很满意

    【讨论】:

    • 请注意,您可以使用 some_dict.keys() 遍历字典键列表。因此,将来如果您想并行遍历键和列表,您可以使用:for i,j in zip(som_list, some_dict.keys()):
    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      首先,don't modify a list during iteration

      您似乎想为一周中的每一天匹配一顿饭。 您可以迭代这些日子:

      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!")
      

      【讨论】:

        猜你喜欢
        • 2015-02-28
        • 1970-01-01
        • 2022-06-15
        • 2022-01-13
        • 1970-01-01
        • 2018-09-18
        • 1970-01-01
        • 1970-01-01
        • 2017-02-25
        相关资源
        最近更新 更多