Python 中的列表理解和 lambda

2024-04-20Python开发问题
7

本文介绍了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.

这篇关于Python 中的列表理解和 lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11