python - 在python中创建可以返回对象的lambda函数

标签 python python-3.x

<分区>

我想将 lambda 用作返回对象的函数。看看 lambda x: print(item) ,正如所写的那样,预期的结果是 holder[str(item)] 将存储一个函数,该函数返回当前项目。但我的代码显示它总是返回最后一项。

为什么会这样?有没有办法传递实际返回项目的函数?

items = [1,2,3]
holder = {}

for item in items:
    holder[str(item)] = lambda x: print(item)

holder['1'](None)
holder['2'](None)
holder['3'](None)

输出:

3
3
3

预期的行为是:

1
2
3

最佳答案

你可以使用 partial()而不是使用 lambda:

from functools import partial


items = [1,2,3]
holder = {}

for item in items:
    holder[str(item)] = partial(print, item)

holder['1'](None)
holder['2'](None)
holder['3'](None)

给出输出:

1 None
2 None
3 None

关于python - 在python中创建可以返回对象的lambda函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57101974/

相关文章:

python - 如何使用 MYSQLdb 在 Python 2.7 中正确创建左连接?

python - 搜索字符串中的特定情况

python - 如何使用变量在 Spyder 控制台中执行 Python 3.3 脚本?

python-3.x - 获取前 10 名和后 10 名特征

python - pyside/pyqt : simple way to bind multiple buttons that shares the same functionality

python - 如何在 python3 中将 24 位 wav 文件转换为 16 位或 32 位文件

python - 如何将列表中的值添加到字典中?

python - opencv - python - 在 cv2.inRange 中使用 HSV 颜色时感到困惑

python - 用于从图像中识别文本的简单 python 库

python-3.x - 如何避免错误的亮点检测?