我正在尝试使用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允许的方式寻址表字段。
发布于 2013-07-22 17:24:26
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)字典是一种很好的数据结构,用于通过路由、分支访问TupLeg对象。您可以通过以下方式访问curr_time
tup_legs[(i,j)].curr_timeitertools模块包含许多算法,允许您以类似于使用itertools的方式访问字典和其他集合。
https://stackoverflow.com/questions/17773989
复制相似问题