使用lambdas进行Python列表理解 [英] Python list comprehension with lambdas

查看:43
本文介绍了使用lambdas进行Python列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行Python 3.4.2,我对代码的行为感到困惑.我正在尝试创建一个递增次数的可调用多项式函数列表:

I'm running Python 3.4.2, and I'm confused at the behavior of my code. I'm trying to create a list of callable polynomial functions with increasing degree:

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

但是出于某种原因,它会这样做:

But for some reason it does this:

print([b(5) for b in bases])
# [25, 25, 25]

为什么bases似乎是列表理解中最后一个lambda表达式的列表重复了?

Why is bases seemingly a list of the last lambda expression, in the list comprehension, repeated?

推荐答案

问题,这是是 在lambda函数中引用的i lambda函数称为.当时i的值是它的最后一个值 绑定到for-loop结束的时间,即2.

The problem, which is a classic "gotcha", is that the i referenced in the lambda functions is not looked up until the lambda function is called. At that time, the value of i is the last value it was bound to when the for-loop ended, i.e. 2.

如果将i绑定到lambda函数的定义中的默认值,则每个i都将成为局部变量,并且在lambda为定义而不是被调用.

If you bind i to a default value in the definition of the lambda functions, then each i becomes a local variable, and its default value is evaluated and bound to the function at the time the lambda is defined rather than called.

因此,当调用lambda时,现在在本地范围中查找i,并使用其默认值:

Thus, when the lambda is called, i is now looked up in the local scope, and its default value is used:

In [177]: bases = [lambda x, i=i: x**i for i in range(3)]

In [178]: print([b(5) for b in bases])
[1, 5, 25]

供参考:

这篇关于使用lambdas进行Python列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆