简体   繁体   English

评估 Python lambda 函数列表仅评估最后一个列表元素

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

I have a list of lambda functions I want to evaluate in order.我有一个要按顺序评估的 lambda 函数列表。 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'. lambda 只是查找 '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 http://docs.python.org/library/functools.html#functools.partial

Not a Python expert, but is it possible that Python is treating i in不是 Python 专家,但 Python 是否可能正在处理i

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.然后,在循环之后, i等于其最后分配的值 (4),并且当函数被调用时,它们遵循它们的i引用,找到 4,并使用该值执行。

Disclosure: probably nonsense.披露:可能是胡说八道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM