Lambdas inside list comprehensions

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

    The problem is that you're not capturing the value of i on each iteration of the list comprehension, you're capturing the variable each time through.

    The problem is that a closure captures variables by reference. In this case you are capturing a variable whose value changes over time (as with all loop variables), so it has a different value when you run it than when you created it.

提交回复
热议问题