【问题标题】:Why python only printing the last key from dictionary?为什么 python 只打印字典中的最后一个键?
【发布时间】: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


    【解决方案1】:

    for 循环key 的每次迭代都会收到一个新值。一旦 for 循环结束,只有 key 的最后一个值被分配给变量 key

    【讨论】:

      【解决方案2】:

      它只打印最后一个键,因为您的 print() 调用在迭代键的 for 循环之外。当程序到达您未注释的print() 时,key 的值是它在循环内分配的最终值。要打印key 的所有值,请取消注释循环内的print(key) 调用。

      【讨论】:

        猜你喜欢
        • 2020-10-21
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多