Skip to main content

## Comments

5 comments

• Gurobi Staff

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ł

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]>
• Gurobi Staff

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ł

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 !!

• Gurobi Staff

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ł

Please sign in to leave a comment.