關於 python 中 lambda 運算式的一些問題
如果你定義如下一個python的匿名函式:
--------------------------------
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
######
-----------------------------------