首页 > 解决方案 > 如何修复这个通过参数化函数列表迭代的“for”循环?

问题描述

我正在使用 Scipy 在 Python 3 中设置约束优化问题。以下代码是我遇到问题的代码的简化版本,但它重现了我正在尝试修复的错误。

在此处输入图像描述

出于代码片段的目的,人们可以忘记有关约束优化和 Scipy 的所有内容。只是该列表P对应于 5 个链接的多边形链的 xy 坐标的扁平列表(如上图所示,不一定按比例绘制)

列表推导cons_length旨在创建计算i链中第一个链接长度的函数列表,即由链接编号参数化的函数列表。

import numpy as np

# number of links in the polygonal chain
N = 5       

# Flattened list of xy coordinates of the vertices of a chain of N links 
# (the length of such a flattened list is 2*N+2), in this case 12. 
P = [1  ,1,  \
     2  ,3,  \
     5  ,8,  \
     13 ,21, \
     34 ,55, \
     89 ,144]

# extract the x coordinate of the ith point
def x(i): 
        return lambda P: P[2*i]

# extract the y coordinate of the ith point
def y(i): 
        return lambda P: P[2*i+1]

# get length of the ith link in the chain 
def length(i):
    def f(P):
        linkvec = np.asarray([ x(i+1)(P) - x(i)(P), \
                               y(i+1)(P) - y(i)(P)])
        result  = np.linalg.norm(linkvec)

        print("---> Calculating length of link: ", i, " :: ", result)
        return result
    return f

# A list of functions, that should ostensibly compute the length of the ith 
# link in the polygonal chain represented by `P`
cons_length = [  lambda P: length(idx)(P)  for idx in range(N)  ]

# For each function in cons_length check what it evaluates to. 
# Why is each for loop evaluating to the same result? 
for i in range(len(cons_length)):
    print("ival: ", i, "link-length: ", cons_length[i](P), "\n" )

在运行代码时,我得到了一个令人费解的输出,如下面的截图所示:

在此处输入图像描述

为什么每个for循环的结果都一样?!这个问题在某种意义上是我昨天在这里问过的一个类似主题的问题的后续:如何在 python 中创建一组参数化函数?

但我相信上面的代码解决了那里提到的绑定问题,特别是在 juanpa.arrivillaga 的评论之一中使用了这个建议

正确的方法是编写一个工厂函数,基本上,您需要创建一个封闭范围,该范围不会更改该变量。我更喜欢类似的东西def func_maker(idx): def f(x): return x + idx; return f(当然,有正确的缩进),然后fns.append(func_maker(idx))在循环中使用。

那么我哪里错了?

标签: python

解决方案


推荐阅读