airport_code = input("Please enter your code")
airport_values = {
'BCN':'Barcelona',
'DUB':'Dublin',
'LIS':'Lisbon',
'LHR':'London Heathrow',
'CDG':'Paris',
'PRG':'Prague',
'RKV':'Reykjavik',
'FCO':'Rome'
}
if airport_code in airport_values:
print('The value is:', airport_values[airport_code])
else:
print("Sorry that item is not in the list ")
嗨,我撰寫了這段代碼來查找用戶輸入的鍵是否與存盤在字典 airport_values 中的值之一匹配。
然后當我查看標記方案時,它使用 for 回圈來遍歷整個字典并使用計數器來檢查每個值。
這是在標記方案中撰寫的偽代碼。
https://i.stack.imgur.com/huUdQ.png
我想知道的是我將如何將它應用于 python 而不是我這樣做的方式。
任何幫助將非常感激。
uj5u.com熱心網友回復:
并不是這個偽代碼并不意味著這是最好的解決方案。在 python 中,您可以直接簽入dict. 另外,python 中沒有 int 索引。
pythonic方式的那種迭代可能是那樣的
for key, value in airport_values.items():
if key == airport_code:
print('The value is:', value)
break
else:
print("Sorry that item is not in the list ")
確切的偽代碼翻譯是
i = 0
airports = list(airport_values.items())
while airports[i][0] != airport_code:
i = 1
print('The value is:', airports[i][1])
uj5u.com熱心網友回復:
for i in airport_values:
if airport_code in airport_values:
print('The value is:', airport_values[airport_code])
break
有關 python for 回圈的更多資訊:https : //www.w3schools.com/python/python_for_loops.asp
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362775.html
上一篇:使用if-else有效地撰寫交換條件(python)
下一篇:我可以在一行上寫箭頭函式嗎
