Python 中的列表理解和 lambda

问题描述

我想创建一个 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 都有自己的 y副本)在 Python 中是否可行?

Is this kind of list comprehension, where every lambda has its own copy of ypossible 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.

你也可以做一个double-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.

相关文章