我正在嘗試使用這本詞典根據用戶輸入進行“檢查”。因此,例如,它將遵循下面使用的類似內容。我認為它可能需要使用“For”回圈?由于人們不理解它,我正在改進這個問題。第一個代碼是我試圖使用字典完成的,以提供下面第二個代碼的結果。
levels = {
'Closet': {'South': 'Hangar'},
'Hangar': {'North': 'Closet', 'East': 'Westwood'},
'Westwood': {'West': 'Hangar'}
}
location = "Closet"
direction = input()
if location == ("Checking dictionary to see which location it is")
if direction == ("Checking dictionary to see if direction is applicable")
location = ("updated location based on direction used with what is in dictionary levels")
IE
if location == "Closet"
if direction == "South"
location = "Hangar"
choices = "North" or "East"
uj5u.com熱心網友回復:
只是嘗試一下您在這里尋找的東西。
def update_location(location, direction, data):
return data.get('location', {}).get(direction, None)
levels = {
'Closet': {'South': 'Hangar'},
'Hangar': {'North': 'Closet', 'East': 'Westwood'},
'Westwood': {'West': 'Hangar'}
}
location = 'Closet'
direction = 'South'
tmp = update_location(location, direction, levels)
if tmp is not None:
location = tmp
這是一本字典。您不需要遍歷它來查找其中的鍵。您只需訪問密鑰。如果傳入的值不在傳入的字典中,則上面的函式將回傳 None 。
uj5u.com熱心網友回復:
我會這樣寫:
if levels.get(location):
possible_direction = levels.get(location)
if possible_direction.get(direction):
location = possible_direction.get(direction)
甚至:
new_location = levels.get(location, {}).get(direction)
if new_location:
location = new_location
甚至:
try:
location = levels[location][direction]
except BaseException:
continue
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375711.html
