python - 如何修复这个通过参数化函数列表迭代的“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))
在循环中使用。
那么我哪里错了?
解决方案
推荐阅读
- php - CakePHP 中的 $this 是什么意思?
- netlogo - 在 Netlogo 中,您可以将列表添加到一起吗?
- firebase - Flutter 上传一批图像并获取所有这些 URL 以存储在 Firestore 中
- python - ndarray 到表(从阶跃函数结果)
- python - 如何将 JSON 转换为格式化的嵌套数组?
- rust - rust 中事实上的字节类型是什么?
- php - 如何通过id从数据库中获取值
- javascript - Jquery 是 JavaScript 的替代品吗?
- angular - 将模型设置为未定义时的角度清除输入
- c++ - 将 exp 用于指数形式 (C++, 1.#INF)