列出Python中的理解和lambda [英] List comprehension and lambdas in Python

查看:62
本文介绍了列出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在Python中都有自己的y副本?

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.

您还可以执行双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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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