Python 调用字典中存储的lambda时出现问题

Python 调用字典中存储的lambda时出现问题,python,python-2.7,dictionary,lambda,Python,Python 2.7,Dictionary,Lambda,我目前正在学习Python,并使用字典和lambda函数的概念。我对以下代码有问题: def helloName(name): print 'hello %s' % name myList = ['one', 'two', 'three'] myDict = {} print '====' * 4 for i in myList: myDict[i] = lambda: helloName(i) print i + ' : ' + str(myDict[i])

我目前正在学习Python,并使用字典和lambda函数的概念。我对以下代码有问题:

def helloName(name):
    print 'hello %s' % name

myList = ['one', 'two', 'three']
myDict = {}

print '====' * 4

for i in myList:
    myDict[i] = lambda: helloName(i)
    print i + ' : ' +  str(myDict[i])

print '====' * 4

myDict['one']()
print myDict['one']
myDict['two']()
print myDict['two']
myDict['three']()
print myDict['three']

print '====' * 4

for i in myList:
    myDict[i]()
    print i + ' : ' +  str(myDict[i])
此脚本的输出为:

================
one : <function <lambda> at 0x0060C330>
two : <function <lambda> at 0x01FB4FB0>
three : <function <lambda> at 0x01FA9570>
================
hello three
<function <lambda> at 0x0060C330>
hello three
<function <lambda> at 0x01FB4FB0>
hello three
<function <lambda> at 0x01FA9570>
================
hello one
one : <function <lambda> at 0x0060C330>
hello two
two : <function <lambda> at 0x01FB4FB0>
hello three
three : <function <lambda> at 0x01FA9570>
================
一:
二:
三:
================
你好,三位
你好,三位
你好,三位
================
你好
一:
两位好
二:
你好,三位
三:
我不理解第二段输出行。我期望的输出与第三块输出行完全相同


您能帮助我理解两种输出之间的差异,并建议修改为具有两倍相同的输出吗?

这是因为Python的闭包属性。要解决这个问题

myDict[i] = lambda i=i: helloName(i)

这个问题已经回答了,,

谢谢,它确实解决了我的问题。你能给我指一些更详细地解释这个闭包属性的文档吗?@Grimmy请检查我在回答中包含的问题:)是的,我正在阅读它。再次感谢您提供的信息:)@Grimmy不客气:)我补充了几个问题,请通读一遍。这是一个非常常见的问题:)