python - 调用存储在字典中的 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])

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>

我不明白第二个输出行 block 。我期望与第三个输出行 block 完全相同的输出。

您能否帮助我了解两个输出之间的差异并建议修改以具有两倍相同的输出?

最佳答案

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

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

此问题已得到解答 hereherehereherehere

关于python - 调用存储在字典中的 lambda 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20659523/

相关文章:

python - 如何使用 Pandas 复制与列表中的日期值匹配的日期时间行

python - 创建一个由 0 和 1 组成的随机数 block

用于替换特定字符串列表的 Python 代码

c# - 为什么 Dictionary 没有 AddRange?

swift - Swift 中的选项和字典

python - 在 Python/Django 中将用户的 facebook/twitter 好友与网站用户进行比较

python - 从列表中获取函数参数

python - 使用正则表达式删除特殊的 Unicode 字符?

python - 在组间使用互斥

python - 将两个列表,一个作为键,一个作为值,合并到 Python 中的字典中