我需要在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})
您可以通过使用
eval
python函数绕过这个问题。在这种特殊情况下,它将完全满足您的要求。如果您有一个字符串,并且希望访问具有此名称的函数,只需编写eval
,f.exeval("cons0")
。参见示例这张照片:
相关问题 更多 >
编程相关推荐