簡體   English   中英

循環遍歷另一個字典內的字典內列表的值

[英]Loop through values of a list inside of a dictionary that's inside another dictionary

我正在嘗試制作一種問答游戲來記住雞尾酒的規格。 我創建了一個名為“雞尾酒”的字典,其中有作為雞尾酒名稱的鍵(Negroni,Aperol Spritz),作為值,每種雞尾酒都有另一個字典,其中包含“烈酒”和“劑量”鍵以及值列表。 我對此進行了編碼並且它有效,但我想知道是否有更好的方法來做到這一點,因為我想添加更多的雞尾酒。 我正在尋找一個循環,當答案正確時,它會“循環”列表中的每個值,而不是我每次都必須使用 if/else 語句手動輸入值。

基本上,如果答案正確,我想自動循環遍歷這兩個:

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

因此,每次循環繼續時,兩行中的 [0] 都應變為1 ,然后變為 [2]。 我希望我解釋清楚。 Ps:我對編程很陌生:)

這是我正在使用的代碼: 代碼

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

有多種選擇可以滿足您的需求,我建議您查看類以獲得更多面向 object 的方法。 話雖如此,讓我們不上課!

注意:我還對您的代碼提出了一些建議,以使其稍微簡單一些並遵守變量命名。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM