在 for 循环中构建多个分段函数 python

Build multiple piecewise function in a for loop python

我试图通过使用 for 循环在 python 中构建多个分段函数。这是一个简单的例子:

a = [(1,2),(3,4)]
weight = {} 
for i in range(2): 
 a_a = a[i][0]
 a_b = a[i][1]
 name = str(i)
 print(a_a,a_b)
 def piece_wise_function(t):
     if t < 0: 
         return a_a 
     else: 
         return a_b 
 weight[name] = piece_wise_function
 print(weight[name](-1))
 print(weight[name](1))

结果如下:

1 2
1
2
3 4
3
4

到目前为止看起来不错,这就是我想要的,第一个分段函数在面对负值时生成 1,在面对正值时生成 2,第二个分段函数生成 3 表示负值,4 表示正值。但是,当我使用分段函数时,

print(weight['1'](-1))
print(weight['0'](-1))
print(weight['1'](1))
print(weight['0'](1))

结果是

3
3
4
4

只是想知道为什么 print(weight['0'](-1))3 而不是我应该拥有的 1 以及为什么 print(weight['0'](1))4 而不是 2.任何帮助将不胜感激。

在您的代码中,for 循环后最后已知的 a_a 值为 3,最后已知的 a_b 值为 4。 这就是为什么您看到 3 而不是 14 而不是 2

例如,如果您将 a 数组值从 a = [(1,2),(3,4)] 更改为 a = [(3,4),(1,2)],则 print(weight['1']((-1))) 的输出将为 1,因为最后一次知道a_a 值将是 1.

试试这个解决方案

a = [(1,2),(3,4)]
weight = {} 

for i in range(2): 
    a_a = a[i][0]
    a_b = a[i][1]
    name = str(i)


    #define a function that returns a function passing a_a and a_b as params
    def piece_wise_function(a_a, a_b):

        #when this function returns its scope will be isolated - notice this is where we are passing in t
        def anonymous( t ):
            #use nonlocal keyword if you need to edit a_a or a_b - if just reading I think you don't need
            nonlocal a_a 
            nonlocal a_b
            if t < 0: 
                return a_a 
            else: 
                return a_b 
        return anonymous
    
    #now call piece wise function which returns anonymous with isolated scope
    weight[name] = piece_wise_function(a_a, a_b) 


print(weight['0'](-1))
print(weight['0'](1))
print(weight['1'](-1))
print(weight['1'](1))

#output
1
2
3
4

您的代码中发生了一些事情。让我们把代码分解一下。

您有一个 for 循环迭代两次:range (2) 等于 01.

循环遍历两次并将值赋给字典weight。分配的值是:

weight['0'](0) = 1
weight['0'](1) = 2
weight['1'](0) = 3
weight['1'](1) = 4

此时a_a的值为3a_b的值为4

当您尝试再次打印该值时,按照您定义函数赋值给字典值的方式,它接受参数并重置字典中的值。

所以当你的新代码执行时:

print(weight['1'](-1))
print(weight['0'](-1))
print(weight['1'](1))
print(weight['0'](1))

它转到函数定义并将 3 和 4 的值重新分配回字典键。这就是打印 3 和 4 的原因。