5

我是一名 AMPL 用户,尝试使用 Python(我的第一个 Python 代码)编写线性编程优化模型。我试图找到如何在复合集上声明索引参数。例如,在 AMPL 中,我会说: Set A Set B Set C param x{A, B, C} param y{A, B, C} param z{A, B, C} 以上的集合和参数可以是通过 AMPL 从数据库中轻松读取。

我从数据库中读取的表有六个字段,即 A、B、C、x、y、z。其中三个是主键(A、B、C),其余的(x、y、z)是在主键上索引的值。

PYTHON PART:我正在使用 PYODBC 模块与 SQL Server 连接。我试过“dict”,但它只能索引一个键。我不确定应该使用哪个 python 功能将前三个字段声明为复合集,并将 x、y 和 z 声明为复合集上的索引值。

import pyodbc    
con = pyodbc.connect('Trusted_Connection=yes', driver = '{SQL Server Native Client 10.0}', server = 'Server', database='db')
cur = con.cursor()
cur.execute("execute dbo.SP @Param =%d" %Param)
result = cur.fetchall()
Comp_Key, x, y, z= dict((A, B, C, [x,y,z]) for A, B, C, x, y, z in result)

当然这是不正确的。我想不出办法来做到这一点。

请帮助我:)提前谢谢!

4

1 回答 1

2

代替这个:

Comp_Key, x, y, z= dict((A, B, C, [x,y,z]) for A, B, C, x, y, z in result)

您可以这样做(如果 A、B、C != B、A、C,即 ABC 的顺序很重要):

final_result = dict(((A, B, C), [x, y, z]) for A, B, C, x, y, z in result)

或者

final_result = {(A, B, C): [x, y, z] for A, B, C, x, y, z in result}  # more readable than first one

或者你可以这样做(如果 A、B、C == B、A、C,即 ABC 的顺序无关紧要):

final_result = dict((frozenset(A, B, C), [x, y, z]) for A, B, C, x, y, z in result)

或者

final_result = {frozenset(A, B, C): [x, y, z] for A, B, C, x, y, z in result}  # more readable than first one
于 2013-07-20T17:19:44.617 回答