问题描述
我想创建一个lambda列表,但效果并不理想.
I wanted to create a list of lambdas, but it didn't quite work out as I hoped.
L = [(lambda x: x/y) for y in range(10)]
我希望列表中的每个函数都将其参数除以其索引,但是所有函数仅按最后一个索引除.
I expected every function in the list to divide its argument by its index, but all functions only divide by the last index.
>>> L[1](5)
0.5555555555555556
>>> L[5](5)
0.5555555555555556
>>> 5/9
0.5555555555555556
这是列表理解吗,每个lambda在Python中都有自己的y
副本?
Is this kind of list comprehension, where every lambda has its own copy of y
possible in Python?
推荐答案
lambda中的y
指的是y
在其来源范围内的最后一个值,即9.
The y
in your lambda refers to the last value that y
had in the scope it came from, i.e., 9.
获得所需行为的最简单方法是在lambda中使用默认参数:
The easiest way to get the behavior you want is to use a default argument in your lambda:
lambda x, y=y: x/y
这将在定义lambda函数时捕获y
的值.
This captures the value of y
at the moment the lambda function is defined.
您还可以执行双lambda",调用返回所需的lambda的函数,并传入所需的y
值:
You can also do a "double-lambda", calling a function that returns the lambda you want, passing in the desired value of y
:
(lambda y: lambda x: x/y)(y)
在这里,每次调用时,外部lambda都会提供一个新的作用域.
Here, the outer lambda provides a new scope each time you call it.
这篇关于列出Python中的理解和lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!