首页 > 解决方案 > 在 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 作为样条线。

标签: pythonlambda

解决方案


lambda依赖于 , 和 的定义mx0并且b来自封闭范围,但是该依赖项是在执行时加载的lambda不是在定义时加载的。因此,您在所有lambdas. 您需要在定义时存储这些值。最简单的方法是使它们成为lambda(在定义时绑定的参数默认值)的默认参数:

    tangent = lambda x, m=m, x0=x0, b=b: m * (x - x0) + b

推荐阅读