关于 python 中使用 lambda 表达式的问题

来源:互联网 发布:免费网页数据采集软件 编辑:程序博客网 时间:2024/06/06 07:45
关于 python 中 lambda 表达式的一些问题

 

如果你定义如下一个python的lambda 函数:

--------------------------------
 def doLambda(val):
  print "value 2:", val

 commands = []
 for value in range(5):
  print "value 1:", value
  commands.append(lambda:doLambda(value))

 for c in commands:
  c()
------------------------------
----

当你调用的时候却发现:doLambda 的value 总是4 ,如下:

>>>
value 1: 0
value 1: 1
value 1: 2
value 1: 3
value 1: 4
value 2: 4
value 2: 4
value 2: 4
value 2: 4
value 2: 4


正确的方式应该如下:

-------------------------------

def wrapper(val):
    def inner():
        print "value 2:", val
    return inner

commands = []
for value in range(5):
    print "value 1:", value
    commands.append(wrapper(value))

for c in commands:
    c()

-------------------------------

>>>
value 1: 0
value 1: 1
value 1: 2
value 1: 3
value 1: 4
value 2: 0
value 2: 1
value 2: 2
value 2: 3
value 2: 4

 

或者:

-----------------------------------

######
>>> commands = []
>>> def sayNumber(n):
...     print n
...
>>> for i in range(5):
...     commands.append((lambda v: lambda: sayNumber(v))(i))
...
>>>
>>> for c in commands:
...     c()
...
0
1
2
3
4
######

-----------------------------------





原创粉丝点击