简体   繁体   English

为什么python只打印字典中的最后一个键?

[英]Why python only printing the last key from dictionary?

I was trying the make a function in python and using a for loop to iterate all keys or values from a dictionary and I was trying to assign a global variable inside the function so I can print the keys outside the function but it was only printing the last key:我正在尝试在 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()

It only prints the last key because your print() call is outside of the for loop that iterates over the keys.它只打印最后一个键,因为您的print()调用在迭代键的for循环之外。 By the time the program gets to your uncommented print() , the value of key is the final value it was assigned inside the loop.当程序到达您未注释的print()key的值是它在循环内分配的最终值。 To print all values of key , uncomment the print(key) call inside the loop.要打印key所有值,请取消注释循环内的print(key)调用。

Every iteration of the for loop key receives a new value. for 循环key每次迭代都会收到一个新值。 Once the for loop ended, only the last value of key is assigned to the variable key .一旦 for 循环结束,只有key的最后一个值被分配给变量key

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM