簡體   English   中英

為什么python只打印字典中的最后一個鍵?

[英]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.

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