Lambdas inside list comprehensions

后端 未结 5 1256
隐瞒了意图╮
隐瞒了意图╮ 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:39

    I'm not sure if it's a bug or a feature, but what's happening is that lambda:i doesn't evaluate i before forming the lambda function. So, it's literally just a function which evaluates whatever the current value of i is. Here's another example of how this happens.

    >>> i=5
    >>> x=lambda:i
    >>> x()
    5
    >>> i=6
    >>> x()
    6
    

    So, obviously, what's happening is the same thing except that i is going to 9 in your examples as it's being assigned through the range 0 through 9 in that order.

    I don't think that there's really any good way to avoid it. Lambda functions in Python are pretty limited. It's not really a functional language at heart.

提交回复
热议问题