[英]Why python only printing the last key from dictionary?
我正在嘗試在 python 中創建一個函數並使用 for 循環來迭代字典中的所有鍵或值,我試圖在函數內分配一個全局變量,以便我可以在函數外打印鍵,但它只打印最后一個鍵:
ships = {
'playerShip1' : cv.imread(r'C:\\Users\\a\\Desktop\\desktopFolders\\pyexample\\seafightShip.jpg', cv.IMREAD_UNCHANGED),
'playership2' : cv.imread(r'C:\\Users\\a\\Desktop\\desktopFolders\\pyexample\\seafightCroped.jpg', cv.IMREAD_UNCHANGED)
}
def att():
global key
for key in ships:
global shipLoc
shipLoc = key
#it works okay here
#print(key)
att()
#quit()
#but it only prints the last key here
print(key)
quit()
它只打印最后一個鍵,因為您的print()
調用在迭代鍵的for
循環之外。 當程序到達您未注釋的print()
, key
的值是它在循環內分配的最終值。 要打印key
所有值,請取消注釋循環內的print(key)
調用。
for 循環key
每次迭代都會收到一個新值。 一旦 for 循環結束,只有key
的最后一個值被分配給變量key
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.