生成器和实际变量值
我需要编写一个返回求和函数列表的函数,将输入数字添加到某个绑定值。这就是我所做的:
def addition_range(start, end):
if start >= end: return None
#res = ( (lambda x: x + i) for i in range(start, end) ) #1
res = [ (lambda x: x + i) for i in range(start, end) ] #2
return res
for i in addition_range(0, 5): print( i(2) )
输出应该是这样的:2,3,4,5,6,但它是 6,6,6,6,6
问题出在“i”变量中,当我调用函数时,它们使用实际的i (4) 的值,不是生成列表期间使用的值。这个问题可以通过使用(#1)代替(#2)来简单地解决,但我感兴趣的是(#2)有解决方案吗?我尝试过
res = [ (lambda x: x + copy.deepcopy(i)) for i in range(start, end) ]
,但没有帮助。
谢谢。
WinXP+Python 3.2
I need to write a function which returns an list of sum functions, adding an input number to some binded value. This is what i did:
def addition_range(start, end):
if start >= end: return None
#res = ( (lambda x: x + i) for i in range(start, end) ) #1
res = [ (lambda x: x + i) for i in range(start, end) ] #2
return res
for i in addition_range(0, 5): print( i(2) )
The output should be like: 2,3,4,5,6 but it's 6,6,6,6,6
The problem is in "i" variable, when i call the functions, they use actual value of i (4), not value used during generation of the list. The problem could be simply solved by using (#1) instead (#2), but i'm interested is there a solution for (#2)? I tried
res = [ (lambda x: x + copy.deepcopy(i)) for i in range(start, end) ]
but it doesn't help.
Thank you.
WinXP + Python 3.2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决此问题的最简单方法是添加虚拟参数:
虚拟参数在定义 lambda 时计算,而您的版本仅在调用 lambda 时计算
i
。旁注:我添加
or None
部分只是为了模拟您的实现的确切行为。返回一个空列表可能比None
更好:The easiest way to solve this is by adding a dummy parameter:
The dummy parameter is evaluated at the time the lambda is defined, whereas your version evaluates
i
only when the lambda is called.Side note: I added the
or None
part only to simulate the exact behaviour of your implementation. It would probably be better to return an empty list instead ofNone
: