-1

我需要在 scipy 中使用多个约束进行优化:

    cons = ({'type': 'eq', 'fun': cons0},\
         {'type': 'eq', 'fun': cons1},{'type': 'eq', 'fun': cons2}, ....)

我尝试通过循环生成它,但 cons0 或 cons1 或 cons3 被视为字符串并且我得到错误。

cons= []

for i in range(3):
     name = cons + str(i)   
     cons.append({'type': 'eq', 'fun': name})
4

1 回答 1

0

您可以使用evalpython 函数绕过它。在这种特定情况下,它将完全按照您的意愿行事。如果您有一个字符串,并且您想访问具有此名称的函数,只需编写evalf.ex 即可eval("cons0")。看例子

def fun0():
    print "Hey!"

def fun1():
    print "there"

funs = {}

for i in range(0,2):
    funs[i] = eval("fun%d" % i)

print funs

funs[0]()
funs[1]()

这打印:

{0: <function fun0 at 0x7f40ce1ab5f0>, 1: <function fun1 at 0x7f40ce1ab668>}
Hey!
there
于 2019-05-09T09:32:11.900 回答