Yuk*_*kiJ 2 python optimization linear-programming python-3.x pulp
在我用 python 中的 PuLP 求解的 LP 模型中,我有两组决策变量,例如
#Variables x
x = LpVariable.dicts("Decision_x",(range(3),range(3)),0,1,LpInteger)
#Variables y
y = LpVariable.dicts("Decision_y",(range(3),range(3)),0,1,LpInteger)
Run Code Online (Sandbox Code Playgroud)
求解模型后,我只对 x[i][j] 取值为 1 的变量感兴趣。我知道
for v in prob.variables():
if v.varValue == 1:
print(v)
Run Code Online (Sandbox Code Playgroud)
我可以打印所有值等于 1 的变量。因此,所有值等于 1 的 x 和所有 y 变量都会被打印。如何设法仅访问 x 变量,以便不打印 y 变量?我尝试过prob.variables(x),prob.variables()[x]但到目前为止没有任何效果。
然后在下一步中,我想提取 x 等于 1 的 x 变量的索引。例如,如果x[1][3] == 1我想找到索引 1 和 3。PuLP 中有什么聪明的方法来实现这一点吗?
x是一个字典。给定两个索引i,j,x[i][j]您有一个pulp.LpVariable.
您事先知道 x 变量的索引,因此一种方法是例如以下
for i,j in itertools.product(range(3),range(3)):
if x[i][j].varValue > 0:
print((i,j), x[i][j].name, x[i][j].varValue)
Run Code Online (Sandbox Code Playgroud)
或者如果您希望保留索引:
x_vars_indices = [(i,j) for i,j in itertools.product(range(3),range(3)) if x[i][j].varValue > 0]
Run Code Online (Sandbox Code Playgroud)
另一种方法是迭代嵌套字典x并获取变量,这些变量是字典最后一层中的值。
x = {0: {0: Decision_x_0_0, 1: Decision_x_0_1, 2: Decision_x_0_2},...
^ ^ ^
| | |
LpVariable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2395 次 |
| 最近记录: |