Lambdas inside list comprehensions

后端 未结 5 1253
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 02:55

I wanted to have a list of lambdas that act as sort of a cache to some heavy computation and noticed this:

>>> [j() for j in [lambda:i for i in rang         


        
5条回答
  •  死守一世寂寞
    2020-12-18 03:38

    The lambda returns the value of i at the time you call it. Since you call the lambda after the loop has finished running, the value of i will always be 9.

    You can create a local i variable in the lambda to hold the value at the time the lambda was defined:

    >>> [j() for j in [lambda i=i:i for i in range(10)]]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Another solution is to create a function that returns the lambda:

    def create_lambda(i):
        return lambda:i
    >>> [j() for j in [create_lambda(i) for i in range(10)]]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    This works because there is a different closure (holding a different value of i) created for each invocation of create_lambda.

提交回复
热议问题