【发布时间】:2013-12-18 13:28:42
【问题描述】:
我目前正在学习 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 python-2.7 dictionary lambda