Weird lambda behaviour in list comprehension [duplicate]

核能气质少年 提交于 2020-01-14 13:52:07

问题


I'm playing with lambda functions inside of list comprehension, and found some weird behaviour

x = [(lambda x: i) for i in range(3)]

print(x[0](0)) #print 2 instead of 0
print(x[1](0)) #print 2 instead of 1
print(x[2](0)) #print 2

Can someone explain why the result is not that I expect?


回答1:


lambdas bind variables themselves, not the values that they had. i is changed to 2 at the end of the list comprehension, so all the lambdas refer to i at that point, and thus refer to 2.

To avoid this, you can use the default argument trick:

[lambda x,i=i:i for i in range(3)]

This binds the value of i in the default argument (which is evaluated at function definition time).



来源:https://stackoverflow.com/questions/15814595/weird-lambda-behaviour-in-list-comprehension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!