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

后端 未结 3 964
旧时难觅i
旧时难觅i 2020-12-17 16:45

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:

  >>> de         


        
相关标签:
3条回答
  • 2020-12-17 17:01

    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))
    
    0 讨论(0)
  • 2020-12-17 17:05

    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

    0 讨论(0)
  • 2020-12-17 17:11

    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 讨论(0)
提交回复
热议问题