我正在尝试在Gurobi中添加变量。我有以下代码:
from gurobipy import *
rangevalue = list(range(8,13))
E = [6, 3, 4, 2, 4, 2, 5, 1, 4, 2]
y = [(m.addVar(name="y%s" % str([i+1, rangevalue[0] - t])
.format(i+1, rangevalue[0] - t))) for i,t in enumerate(E)]
m.update()
y #You can directly run this code and see the following output:
[<gurobi.Var y[1, 2]>,
<gurobi.Var y[2, 5]>,
<gurobi.Var y[3, 4]>,
<gurobi.Var y[4, 6]>,
<gurobi.Var y[5, 4]>,
<gurobi.Var y[6, 6]>,
<gurobi.Var y[7, 3]>,
<gurobi.Var y[8, 7]>,
<gurobi.Var y[9, 4]>,
<gurobi.Var y[10, 6]>]
这就是我想要的。但是,我还希望在rangevalue
[1]
,[2]
,[3]
,[4]
..... max rangevalue
时添加更多变量}。我的范围值不限于范围(8,13),它可以更高。那么,基于此,我如何构造一个循环来添加所有y
个变量?
这是我失败的尝试:
for k in range(rangevalue)
y[k] = [(m.addVar(name="y%s" % str([i+1, rangevalue[k] - t])
.format(i+1, rangevalue[k] - t))) for i,t in enumerate(E)]
答案 0 :(得分:0)
好吧,我刚刚找到了自己的答案,并在这里分享。也许有人可以受益:
for i in range(I):
for k in range(len(rangevalue)):
t = E[i]
y[i+1, rangevalue[k] - t] = m.addVar(vtype=GRB.BINARY,
name="y%s" % str([i+1, rangevalue[k] - t]))
m.update()
y
输出:
{(1, 2): <gurobi.Var y[1, 2]>,
(1, 3): <gurobi.Var y[1, 3]>,
(1, 4): <gurobi.Var y[1, 4]>,
(1, 5): <gurobi.Var y[1, 5]>,
(1, 6): <gurobi.Var y[1, 6]>,
(2, 5): <gurobi.Var y[2, 5]>,
(2, 6): <gurobi.Var y[2, 6]>,
(2, 7): <gurobi.Var y[2, 7]>,
(2, 8): <gurobi.Var y[2, 8]>,
(2, 9): <gurobi.Var y[2, 9]>,
(3, 4): <gurobi.Var y[3, 4]>,
(3, 5): <gurobi.Var y[3, 5]>,
(3, 6): <gurobi.Var y[3, 6]>,
(3, 7): <gurobi.Var y[3, 7]>,
(3, 8): <gurobi.Var y[3, 8]>,
(4, 6): <gurobi.Var y[4, 6]>,
(4, 7): <gurobi.Var y[4, 7]>,
(4, 8): <gurobi.Var y[4, 8]>,
(4, 9): <gurobi.Var y[4, 9]>,
(4, 10): <gurobi.Var y[4, 10]>,
(5, 4): <gurobi.Var y[5, 4]>,
(5, 5): <gurobi.Var y[5, 5]>,
(5, 6): <gurobi.Var y[5, 6]>,
(5, 7): <gurobi.Var y[5, 7]>,
(5, 8): <gurobi.Var y[5, 8]>,
(6, 6): <gurobi.Var y[6, 6]>,
(6, 7): <gurobi.Var y[6, 7]>,
(6, 8): <gurobi.Var y[6, 8]>,
(6, 9): <gurobi.Var y[6, 9]>,
(6, 10): <gurobi.Var y[6, 10]>,
(7, 3): <gurobi.Var y[7, 3]>,
(7, 4): <gurobi.Var y[7, 4]>,
(7, 5): <gurobi.Var y[7, 5]>,
(7, 6): <gurobi.Var y[7, 6]>,
(7, 7): <gurobi.Var y[7, 7]>,
(8, 7): <gurobi.Var y[8, 7]>,
(8, 8): <gurobi.Var y[8, 8]>,
(8, 9): <gurobi.Var y[8, 9]>,
(8, 10): <gurobi.Var y[8, 10]>,
(8, 11): <gurobi.Var y[8, 11]>,
(9, 4): <gurobi.Var y[9, 4]>,
(9, 5): <gurobi.Var y[9, 5]>,
(9, 6): <gurobi.Var y[9, 6]>,
(9, 7): <gurobi.Var y[9, 7]>,
(9, 8): <gurobi.Var y[9, 8]>,
(10, 6): <gurobi.Var y[10, 6]>,
(10, 7): <gurobi.Var y[10, 7]>,
(10, 8): <gurobi.Var y[10, 8]>,
(10, 9): <gurobi.Var y[10, 9]>,
(10, 10): <gurobi.Var y[10, 10]>}