python在scipy中动态创建约束字典

python在scipy中动态创建约束字典,python,loops,dictionary,optimization,minimize,Python,Loops,Dictionary,Optimization,Minimize,我正在使用scipy.optimize.minimize(…)例程,需要指定约束参数,其形式如下: N = 50 cons = ({'type': 'ineq', 'fun': lambda x: x[0]<x[1]}, {'type': 'ineq', 'fun': lambda x: x[1]<x[2]}, {'type': 'ineq', 'fun': lambda x: x[2]<x[3]},

我正在使用scipy.optimize.minimize(…)例程,需要指定约束参数,其形式如下:

N = 50
cons = ({'type': 'ineq', 'fun': lambda x: x[0]<x[1]},
               {'type': 'ineq', 'fun': lambda x: x[1]<x[2]},
               {'type': 'ineq', 'fun': lambda x: x[2]<x[3]}, 
               ...)
N=50

cons=({'type':'ineq','fun':lambda x:x[0]这个问题很难解决,因为python是如何实现其后期绑定闭包的……请参阅。 本质上,您需要这样做:

N = 50
cons = tuple({'type':'ineq','fun':(lambda x, i=i: x[i] < x[i + 1])} for i in range(N))
print(cons[0]['fun']((1, 2, 3)))
N=50
cons=tuple({'type':'ineq','fun':(lambda x,i=i:x[i]
这个问题很难解决,因为python后期绑定闭包是如何实现的……请参阅。 本质上,您需要这样做:

N = 50
cons = tuple({'type':'ineq','fun':(lambda x, i=i: x[i] < x[i + 1])} for i in range(N))
print(cons[0]['fun']((1, 2, 3)))
N=50
cons=tuple({'type':'ineq','fun':(lambda x,i=i:x[i]
你想在第一个代码块中创建什么?比如
[{'type':'ineq','fun':lambda x:x[i]
@yatu i虽然如此,但是
lambda
让事情变得棘手。你想在第一个代码块中创建什么?比如
[{'type':'ineq','fun':lambda x:x[i]
@yatu i虽然如此,但是
lambda
使事情变得棘手。
N = 50
cons = tuple({'type':'ineq','fun':(lambda x, i=i: x[i] < x[i + 1])} for i in range(N))
print(cons[0]['fun']((1, 2, 3)))