python - 在 for 循环中创建的 lambda 函数被覆盖
问题描述
执行以下代码
# horizontals : list of functions
# A list of spline functions
# vertical : function
# Line function
#
# All are given in the form f(x) = y
def mwe(horizontals, vertical):
tangents = []
for spline in horizontals:
x0, b = intersection(spline, vertical) # Returns (float, float)
m = float(spline(x, 1))
tangent = lambda x: m * (x - x0) + b
tangents.append(tangent)
print(tangent(0))
print(tangents[-1](0))
print()
for tangent in tangents:
print(tangent(0))
导致此输出:
715.2170619670379
715.2170619670379
851.5168419777629
851.5168419777629
992.2507908527389
992.2507908527389
992.2507908527389
992.2507908527389
992.2507908527389
我不明白为什么列表中的所有函数都被覆盖了?表达式中只有原始数据类型(浮点数)不会导致任何引用问题,不是吗?
编辑:如果重要的话,代码使用 numpy/scipy 作为样条线。
解决方案
您lambda
依赖于 , 和 的定义m
,x0
并且b
来自封闭范围,但是该依赖项是在执行时加载的lambda
,而不是在定义时加载的。因此,您在所有lambda
s. 您需要在定义时存储这些值。最简单的方法是使它们成为lambda
(在定义时绑定的参数默认值)的默认参数:
tangent = lambda x, m=m, x0=x0, b=b: m * (x - x0) + b
推荐阅读
- python - 我应该如何使用 TF-IDF 对我收集的数据进行文本分类?
- bixby - 如何实现从 Bixby 到 Android 应用程序的这种打孔?
- git - 重置后Git错误'更新被拒绝,因为您当前分支的尖端落后'
- visual-studio-code - ( Ctrl + / ) 快捷方式在 VSC 中无法正常工作
- sql-server - Calculating age based on a column that has only years in it in SQL Server
- python - 如何将两个对象合并成一个包含两个元素的元组?
- azure - 为 Azure Blockchain Workbench 部署智能合约时出错
- php - PHP 填补数组空洞
- javascript - 如何使用反应导航?
- javascript - 如何使用 CSS 创建可悬停的彩虹?