How does a lambda function refer to its parameters in python?

前端 未结 4 1750
余生分开走
余生分开走 2021-01-05 17:09

I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like

fs = [         


        
4条回答
  •  醉酒成梦
    2021-01-05 17:36

    It looks a bit messy, but you can get what you want by doing something like this:

    >>> fs = [(lambda y: lambda x: x + y)(i) for i in xrange(10)]
    >>> [f(0) for f in fs]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Normally Python supports the "closure" concept similar to what you're used to in Javascript. However, for this particular case of a lambda expression inside a list comprehension, it seems as though i is only bound once and takes on each value in succession, leaving each returned function to act as though i is 9. The above hack explicitly passes each value of i into a lambda that returns another lambda, using the captured value of y.

提交回复
热议问题