有什么方法可以在 PuLP 优化中从字符串调用 LpVariables 吗?
Is there any way to call LpVariables from string in PuLP optimization?
在 PuLP 优化程序中,我想从 str 列表中调用定义的 LpVariable 值。
我试图通过某种方式转换 'x2',但我做不到。
除了使用 many IF/ELIF list if test_str=='x1': ...
?
之外,有什么办法可以做到这一点吗?
from pulp import *
def pulp_test():
# define the problem
prob = LpProblem("The_Problem", LpMinimize)
x1 = LpVariable('x1', 0, None, LpContinuous)
x2 = LpVariable('x2', 0, None, LpContinuous)
x3 = LpVariable('x3', 0, None, 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
在 PuLP 优化程序中,我想从 str 列表中调用定义的 LpVariable 值。
我试图通过某种方式转换 'x2',但我做不到。
除了使用 many IF/ELIF list if test_str=='x1': ...
?
from pulp import *
def pulp_test():
# define the problem
prob = LpProblem("The_Problem", LpMinimize)
x1 = LpVariable('x1', 0, None, LpContinuous)
x2 = LpVariable('x2', 0, None, LpContinuous)
x3 = LpVariable('x3', 0, None, 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