문제

I am an AMPL user trying to write a linear programming optimization model using Python (My first Python code). I am trying to find how to declare indexed parameters over compound sets. For example, in AMPL, i would say: Set A Set B Set C param x{A, B, C} param y{A, B, C} param z{A, B, C} The above sets and parameters can be easily read from a database via AMPL.

The table that I read from the database has six fields i.e. A, B, C, x, y, z. Three of them are primary keys (A, B, C) and the rest (x,y,z) are values indexed over the primary keys.

PYTHON PART: I am using PYODBC module to connect with SQL Server. I tried "dict" but it can index over only one key. I am not sure which python feature should I use to declare the first three fields as a compound set and x, y and z as values indexed over the compound set.

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)

Ofcourse it is not correct. I cannot think about a way to do this.

Please help me :) Thanks in advance!

도움이 되었습니까?

해결책

In place of this:

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

You could do this (if A, B, C != B, A, C, i.e. order of A B C matters):

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

OR

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

Or you could do this (if A, B, C == B, A, C, i.e. order of A B C does not matter):

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

OR

final_result = {frozenset(A, B, C): [x, y, z] for A, B, C, x, y, z in result}  # more readable than first one
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top