我正在尝试使用 Gurobi Python API 将我的 OPL 模型转换为 Python。我想知道Python 中是否存在与OPL 元组结构等效的结构。最好举个例子:
tuple tup_Leg
{
key string Route;
key string Leg;
int Curr_Time;
int Max_Time;
int Min_Time;
float Cube;
}
{tup_Leg} set_Leg = DBRead(db,"Exec SPROC ?")(Param);'
Route和Leg是我的优化模型中的集合; Curr_Time、Min_Time、Max_Time 和 Cube 是在 Route 和 Leg 集上索引的参数。
在 OPL 中,由于我将 Route 和 Leg 定义为键,因此可以将它们视为集合,并且可以对它们进行索引。例如,要解决 Curr_Time,我可以这样做:
i.Curr_Time : i in set_Leg
我一直在努力在 Python 中找到与此等效的内容。到目前为止,我在 Python 中有以下内容:
import pyodbc
Param = 123
con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server Native Client 10.0}', server = 'Server', database='db')
cur = con.cursor()
cur.execute("execute SPROC @Param =%d" %Param)
result = cur.fetchall()
tup_Leg = dict(((Route, Leg), [Curr_Time, Min_Time, Max_Time, Cube]) for Route, Leg, Curr_Time, Min_Time, Max_Time, Cube in result)
我不确定如何解决 Curr_Time 或 Min_Time 问题?到目前为止我已经:
for i,j in tup_Leg:
Curr_Time, Min_Time, Max_Time, Cube = tup_Leg[(i,j)]
除了听写之外,还有更好的方法吗?我想知道是否还有其他选项可以让我以 OPL 允许的方式处理表字段。
最佳答案
named tuples类似于 opl 元组。
from collections import namedtuple
TupLeg = namedtuple('TupLeg', ['route', 'leg',
'curr_time', 'min_time', 'max_time' 'cube'])
tup_legs = dict((result[0], result[1]), TupLeg(*result) for result in cur)
字典是一种很好的数据结构,用于通过路径、leg 访问 TupLeg 对象。您可以通过以下方式访问 curr_time
tup_legs[(i,j)].curr_time
itertools模块包含许多算法,允许您以类似于您习惯使用 opl 的方式访问字典和其他集合。
关于python - ILOG OPL 与 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17773989/