python - 为什么python只打印字典中的最后一个键?
问题描述
我正在尝试在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
遍历键的循环之外。当程序到达你的 uncommentedprint()
时, 的值key
是它在循环内分配的最终值。要打印 的所有值key
,请取消注释print(key)
循环内的调用。
推荐阅读
- docker - 如何在 /mosquitto/data MQTT mosquitto 中存储消息?
- python-3.x - 将新列名映射到 Pandas 中的数据框
- java - 在 Java 的类加载阶段,符号引用如何解析为直接引用?
- azure - 如何在 Azure 数据工厂 V2 中设置看似循环但实际上不是循环的依赖项
- c - 为什么我的动态分配的数组不能在它的函数之外被访问?[C]
- c# - Task.WhenAll() 包含大量任务
- nlp - 如何使 spacy 规则库仅匹配给定模式之间的内容
- ruby-on-rails - 以 Rails 多步骤形式管理时区
- r - 我如何有一个在 r 中乘以 2 个函数的函数?
- wordpress - 仅在 all_items 中显示某些自定义帖子