开发者

Evaluating a list of python lambda functions only evaluates the last list element [duplicate]

开发者 https://www.devze.com 2023-03-06 20:38 出处:网络
This question already has answers here: Creating functions (or lambdas) in a loop (or comprehension) (6 answers开发者_如何转开发)
This question already has answers here: Creating functions (or lambdas) in a loop (or comprehension) (6 answers开发者_如何转开发) Closed 7 months ago.

I have a list of lambda functions I want to evaluate in order. I'm not sure why, but only the last function gets evaluated. Example below:

  >>> def f(x,z):
  ...     print "x=",x,", z=",z
  ... 
  >>> 
  >>> g = lambda x : f(x,13)
  >>> g(2)
  x= 2 , z= 13    # As expected
  >>> 
  >>> lst=[]
  >>> 
  >>> for i in range(0,5): 
  ...    lst.append(lambda x: f(x,i))
  ... 
  >>> print lst
  [<function <lambda> at 0x10341e2a8>, <function <lambda> at 0x10341e398>, <function <lambda> at 0x10341e410>, <function <lambda> at 0x10341e488>, <function <lambda> at 0x10341e500>]
  >>> 
  >>> for fn in lst:
  ...   fn(3)
  ... 
  x= 3 , z= 4 # z should be 0
  x= 3 , z= 4 # z should be 1
  x= 3 , z= 4 # z should be 2
  x= 3 , z= 4 # z should be 3
  x= 3 , z= 4 # as expected.

I think only the last one is getting executed, but not the others. Any ideas? Thanks!


The lambda is just looking up the global value of 'i'.

Try the following instead:

for i in range(0,5):
  lst.append(lambda x, z=i: f(x,z))


try using partial, works for me:

from functools import partial

def f(x,z):
    print "x=",x,", z=",z

lst = [ partial(f,z=i) for i in range(5) ]

for fn in lst:
    fn(3)

http://docs.python.org/library/functools.html#functools.partial


Not a Python expert, but is it possible that Python is treating i in

lst.append(lambda x: f(x,i))

as a reference? Then, after the loop, i is equal to its last assigned value (4), and when the functions are called, they follow their i reference, find 4, and execute with that value.

Disclosure: probably nonsense.

0

精彩评论

暂无评论...
验证码 换一张
取 消