I have an array of functions, for example:
>>> def f():
... print "f"
...
>>> def g():
... print "g"
...
>>> c=[f,g]
Then i try to create two lambda functions:
>>> i=0
>>> x=lambda: c[i]()
>>> i+=1
>>> y=lambda: c[i]()
And then, call them:
>>> x()
g
>>> y()
g
Why c[i] in lambda are the same?
解决方案
That's because the lambda function is fetching the value of the global variable i at runtime:
>>> i = 0
>>> x=lambda z = i : c[z]() #assign the current value of `i` to a local variable inside lambda
>>> i+=1
>>> y =lambda z = i : c[z]()
>>> x()
f
>>> y()
g