Sort Decision variables' value in Gurobi Python
AnsweredI have a decision variables list as follows :
vars=[ <gurobi.Var x1,5,>, <gurobi.Var x5,1,>, <gurobi.Var x1,22,>, <gurobi.Var x22,1,>]
if I want to sort the elements based on the indices of each var as follows :
vars=[ <gurobi.Var x1,5,>,, <gurobi.Var x1,22,>, <gurobi.Var x5,1,>, <gurobi.Var x22,1,>]
I am using the following :
vars.sort(key=lambda k: x[k], reverse=False)
but it gives an error message

Hi Ahmad,
Please always provide a minimal working example to make your issue reproducible and post the error message you get.
Before optimization has been performed you can only really sort your variables w.r.t. their VarName attribute. Unless you want to sort the variables w.r.t. the indices you used.
Best regards,
Jaromił0 
Hi Jaromil
I am so sorry if the issue was not clear, let me give more details :
I have a model where the variable x is defined as follow :
x = {}
for (i, j) in E:
x[i, j] = model.addVar(vtype=GRB.BINARY, name="x%d,%d," % (i, j))where E is a set of edges, now in a specific step of my work I want to get the x by using
variables = model.getVars()
and I want the vars to be sorted based on their indices (as I mentioned in the previous example) by
modelvars = variables.sort(key=lambda k: x[k], reverse=False)
but I got the following error message
File "E:/Induced path/Benders/LIP2_callback.py", line 300, in <lambda>
modelvars = variables.sort(key=lambda k: x[k], reverse=False)
KeyError: <gurobi.Var x[1,2]>0 
Hi Ahmad,
Since you are naming your variables appropriately, one easy way to sort the variables list would be
variables.sort(key=lambda x: x.VarName)
Best regards,
Jaromił0 
Hi Jaromil
your suggestion kind of works, the problem that by using the x.VarName it takes x,1,11 to be before x,1,2 in the sorted list !!
0 
Hi Ahmad,
In this case, you have to go a bit further and provide a tuple for sorting consisting of numbers
variables.sort(key=lambda x: (float(x.VarName.split(",")[0][1:]),float(x.VarName.split(",")[1])))
The VarName is spit at "," providing 3 strings \(\texttt{xi}\) , \(\texttt{j}\) and an empty character.
The tuple for the \(\texttt{lambda}\) function consists of two entries, the first index and the second one in VarName.
Best regards,
Jaromił1
Please sign in to leave a comment.
Comments
5 comments