【发布时间】:2021-01-19 18:15:44
【问题描述】:
我正在尝试在 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()
【问题讨论】:
标签: python python-3.x list dictionary