Python 中的列表推导式和 lambdas [英] List comprehension and lambdas in Python

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

问题描述

我想创建一个 lambdas 列表,但结果并不如我所愿.

L = [(lambda x: x/y) for y in range(10)]

我希望列表中的每个函数都将其参数除以它的索引,但所有函数只除以最后一个索引.

<预><代码>>>>L[1](5)0.5555555555555556>>>L[5](5)0.5555555555555556>>>5/90.5555555555555556

这种列表推导式,其中每个 lambda 都有自己的 y 副本在 Python 中可能吗?

解决方案

lambda 中的 y 指的是 y 在它来自的范围内的最后一个值,即 9.

获得所需行为的最简单方法是在 lambda 中使用默认参数:

lambda x, y=y: x/y

这会在定义 lambda 函数时捕获 y 的值.

你也可以做一个double-lambda",调用一个返回你想要的lambda的函数,传入y的期望值:

(lambda y: lambda x: x/y)(y)

在这里,外部 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

Is this kind of list comprehension, where every lambda has its own copy of ypossible in Python?

解决方案

The y in your lambda refers to the last value that y had in the scope it came from, i.e., 9.

The easiest way to get the behavior you want is to use a default argument in your lambda:

lambda x, y=y: x/y

This captures the value of y at the moment the lambda function is defined.

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)

Here, the outer lambda provides a new scope each time you call it.

这篇关于Python 中的列表推导式和 lambdas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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