2013-07-21 17 views
1

我正在嘗試使用Gurobi Python API將我的OPL模型轉換爲Python。我想知道在Python中是否有相當於OPL元組結構。最好舉例說明:ILOG OPL與Python

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 and 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允許的方式處理表格字段。

回答

1

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) 

一個dict是一個很好的數據結構,用於通過路徑,腿來訪問TupLeg對象。您可以通過

tup_legs[(i,j)].curr_time 

itertools模塊包含了很多的算法,將允許您訪問詞典和其他收藏品類似,你習慣把OPL什麼方式訪問curr_time。

+0

完美答案! –