【发布时间】:2015-07-10 12:27:55
【问题描述】:
我使用 scipy optimize 最小化包。为了为我的问题提供约束,我需要创建一个庞大的元组。我这样做是通过以下方式:
c0 = [];
count = 0;
for i in range(0, Nx):
for j in range(0, Ny):
c0.append({'type': 'eq', 'fun': lambda x: x[count]*x[count] + x[T + count]*x[T + count] + x[2*T + count]*x[2*T + count] - 1.});
count+=1;
cons = tuple(c0);
但是当最小化器使用它们时,它总是取count的最终值,这显然会导致index out of bounds错误。尝试del(count) 导致另一个错误,所以我想我对 lambda 函数使用的 python 方式的理解有问题。也许有更好的使用切片和东西的python风格的方式?将不胜感激。
【问题讨论】:
-
lambdas 中的名称将评估为 lambda 运行时名称的值,而不是创建时的值。这解释了您的终端计数问题。请参阅Local variables in Python nested functions 了解更多信息。