问题描述
在PuLP优化程序中,我想从str列表中调用定义的LpVariable值。
我试图通过某种方式转换“x2”,但我不能。
除了使用许多 IF/ELIF 列表 if test_str=='x1': ...
之外,还有什么办法可以做到这一点?
from pulp import *
def pulp_test():
# define the problem
prob = LpProblem("The_Problem",LpMinimize)
x1 = LpVariable('x1',None,LpContinuous)
x2 = LpVariable('x2',LpContinuous)
x3 = LpVariable('x3',LpContinuous)
prob += 3 * x1 + 11 * x2 + 2 * x3
prob += -1 * x1 + 3 * x2 <= 5
prob += 3 * x1 + 3 * x2 <= 4
prob += 3 * x2 + 2 * x3 <= 6
prob += 3 * x1 + 5 * x3 >= 4
status = prob.solve()
test_str = 'x2'
print("type(x2): ",type(x2))
print("type('x2'): ",type(test_str))
print("value(x2): ",value(x2))
# want to call LpVariable from str list
print("value(convert from str 'x2'): ",value(pulp.LpVariable(test_str)))
pulp_test()
结果是,
type(x2): <class 'pulp.pulp.LpVariable'>
type('x2'): <class 'str'>
value(x2): 0.0
value(convert from str 'x2'): None
解决方法
检查 LpVariable.dicts
方法。它将创建一个变量字典。以下是使用它的示例:https://coin-or.github.io/pulp/CaseStudies/a_blending_problem.html
从那个例子:
from pulp import *
Ingredients = ['CHICKEN','BEEF','MUTTON','RICE','WHEAT','GEL']
ingredient_vars = LpVariable.dicts("Ingr",Ingredients,0)
如果你这样做:
ingredient_vars['CHICKEN'] # you get the variable for chicken