• Gurobi Staff

Hi Robert,

Assuming you want to look for variables whose names start with these letters, you can use the following:

for v in m.getVars():    if v.varName.startswith("AA"):        print("AA")    elif v.varName.startswith("BB"):        print("BB")

However, it's usually possible to avoid searching for variables by name. This can be done by creating a variable from the object returned by the addVar() or addVars() method. For example,

aa = m.addVars(5, 5, name="AA")

creates 25 variables with names AA[0,0], AA[0,1], ..., AA[4,4]. In this example, aa is a tupledict object that contains these variables. This object is very useful, because it allows you direct access to the set of "AA" variables:

for v in aa:    print(v.varName)

Thus, the aa tupledict object can be used to build constraints, retrieve variable values, etc. I hope this helps!

Hi Eli,

Thank you very much. It works!

Best

Robert



Hell Eli,

I have a code as below:

for v in m.getVars():
print('%s %g' % (v.varName, v.x))

The varName is 3 by 2 dimension, so x is 3 by 2 dimension too

When I print, its output is like the following

A[1,1] 1
A[1,2] 3
A[2,1] 2
A[2,2] 4
A[3,1] 5
A[3,2] 3

is there any way to print a line for each row, like as below:?

A[1,1] 1   A[1,2] 3
A[2,1] 2   A[2,2] 4
A[3,1] 5   A[3,2] 3

Thank you very much

Robert

• Gurobi Staff

Hi Robert,

A = m.addVars(range(1,4), range(1,3), name="A")

you can print a line for each row as follows:

for i in range(1, 4):    alist = ["%s %g" % (v.varName, v.X) for v in A.select(i, '*')]    print("\t".join(alist))

This code snippet uses the select() method of the tupledict object, as well as a Python list comprehension. An example of the output:

A[1,1] 1        A[1,2] 3   A[2,1] 2        A[2,2] 4   A[3,1] 5        A[3,2] 3

I hope this helps!

Eli

Hi Eli,

Thank you very much for your help. It seems not easy to write the codes. I will give a try.

Sincerely,

Robert