【问题标题】:Loop through values of a list inside of a dictionary that's inside another dictionary循环遍历另一个字典内的字典内列表的值
【发布时间】:2021-01-04 19:52:30
【问题描述】:

我正在尝试制作一种问答游戏来记住鸡尾酒的规格。 我创建了一个名为“鸡尾酒”的字典,其中有作为鸡尾酒名称的键(Negroni,Aperol Spritz),作为值,每个鸡尾酒都有另一个字典,其中包含“烈酒”和“剂量”键以及值列表。我对此进行了编码并且它有效,但我想知道是否有更好的方法来做到这一点,因为我想添加更多的鸡尾酒。 我正在寻找一个循环,当答案正确时,它会“循环”列表中的每个值,而不必每次都使用 if/else 语句手动输入值。

如果答案正确,基本上我想自动循环遍历这两个:

cocktails["negroni"]["spirits"][0]
cocktails["negroni"]["ml"][0]

所以每次循环继续时,[0] 应该变为1,然后在两行中变为 [2]。 我希望我解释清楚。 Ps:我对编程很陌生:)

这是我正在使用的代码: code

cocktails = {
    "negroni": {
       "spirits": ["gin", "vermouth", "campari"],
       "ml": [25, 25, 25],
    },
    "aperol_spritz": {
        "spirits": ["aperol", "prosecco", "soda"],
        "ml": [50, 50, "top"]
    }
}
cocktail = "Negroni"
print(cocktail)
stop_quiz = True
while stop_quiz:
    guess = int(input(cocktails["negroni"]["spirits"][0] + ": "))
    if guess != cocktails["negroni"]["ml"][0]:
        continue
    else:
        guess = int(input(cocktails["negroni"]["spirits"][1] + ": "))
        if guess != cocktails["negroni"]["ml"][1]:
            continue
        else:
            guess = int(input(cocktails["negroni"]["spirits"][2] + ": "))
            if guess != cocktails["negroni"]["ml"][2]:
                continue
            else:
                print("You know how to make a " + cocktail + "!")
                answer = input("Do you want to play again? ")
                if answer == "yes":
                    continue
                elif answer == "no":
                    print("See you soon!")
                    stop_quiz = False

【问题讨论】:

  • 我建议看看classes。使用类时,您可以创建一个函数来验证类的每个属性的输入(在所有属性上创建一个 for 循环,如果所有属性都正确,则返回 True,否则返回 False
  • 谢谢,我还没上课呢:)那我以后会更新项目的!

标签: python python-3.x list loops dictionary


【解决方案1】:

有多种选择可以得到你想要的,我建议看看类以获得更面向对象的方法。话虽如此,让我们不上课!

注意:我还对您的代码提出了一些建议,以使其稍微简单一些并遵守变量命名。

cocktails = {
    "negroni": {
        "spirits": ["gin", "vermouth", "campari"],
        "ml": [25, 25, 25],
    },
    "aperol_spritz": {
        "spirits": ["aperol", "prosecco", "soda"],
        "ml": [50, 50, "top"]
    }
}

游戏:

cocktail = 'negroni'
print(cocktail)

stop_quiz = True
while stop_quiz:

    for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
        guess = int(input(f"{spirit}: "))
        while guess != amount:
            print("You are wrong :( , try again!")
            guess = int(input(f"{spirit}: "))

    print("You know how to make a " + cocktail + "!")
    answer = input("Do you want to play again? ")
    if answer == "yes":
        continue
    elif answer == "no":
        print("See you soon!")
        stop_quiz = False

说明

我们利用以下两点:

  1. zip 内置的 Python
  2. 一种do while循环。

zip 迭代器创建一个包含您的精神和答案的循环:

for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):

现在您可以迭代所有不同的精神,并且您已经有了可以比较的正确答案。

在 Python 中,默认情况下没有 do while 循环这样的东西。但是我们可以模拟询问某事的行为,直到我们得到我们想要的。我们首先要求输入金额,如果这不是我们想要的,我们会再次询问(并再次...)。

guess = int(input(f"{spirit}: "))
while guess != amount:
    print("You are wrong :( , try again!")
    guess = int(input(f"{spirit}: "))

当玩家成功猜出所有精神数量后,您将收到结束消息并提示您再次播放。

改进

现在有一些事情可以改变以改进代码:

  • stop_quiz 的值是True,但将其设为False 更有意义,并在while 循环中检查相反的条件。或者您可以将名称更改为例如running
  • 最后提示yesno 问题,但如果这是True,则继续yes 问题。那么为什么要检查它呢?也没有 else 语句,所以你真的只需要检查 no 值。
cocktail = 'negroni'  # same as list(cocktails)[0]
print(cocktail)

running = True
while running:

    for spirit, amount in zip(cocktails[cocktail]['spirits'], cocktails[cocktail]['ml']):
        guess = int(input(f"{spirit}: "))
        while guess != amount:
            print("You are wrong :( , try again!")
            guess = int(input(f"{spirit}: "))

    print("You know how to make a " + cocktail + "!")
    answer = input("Do you want to play again? ")

    if answer == 'no':
        print("See you soon!")
        running = False

【讨论】:

  • 非常感谢,这真的很有帮助!
最近更新 更多