首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ILOG OPL与Python

ILOG OPL与Python
EN

Stack Overflow用户
提问于 2013-07-21 23:36:16
回答 1查看 494关注 0票数 1

我正在尝试使用Gurobi Python API将我的OPL模型转换为Python。我想知道在Python中是否有OPL元组结构的等价物。最好给出一个例子:

代码语言:javascript
复制
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,我可以这样做:

代码语言:javascript
复制
i.Curr_Time : i in set_Leg 

我一直在努力在Python中找到与此类似的东西。到目前为止,我用Python编写了以下代码:

代码语言:javascript
复制
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?到目前为止,我有:

代码语言:javascript
复制
for i,j in tup_Leg:
    Curr_Time, Min_Time, Max_Time, Cube = tup_Leg[(i,j)]

有没有比字典更好的方法来做这件事?我想知道是否有其他选项可以让我以OPL允许的方式寻址表字段。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-22 17:24:26

named tuples类似于opl元组。

代码语言:javascript
复制
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

代码语言:javascript
复制
tup_legs[(i,j)].curr_time

itertools模块包含许多算法,允许您以类似于使用itertools的方式访问字典和其他集合。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17773989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档