简体   繁体   中英

Changing a 3D array to a 2D array that includes a list in Python/Pulp

I am using Solverstudio (with the Pulp solver) and i am trying to get a 2D output (onto a spreadsheet) from a 3D variable that has been found, for certain values of that variable.

Ive tried:

for (m,c,t) in mct:                 
 if Ymct[m][c][t].varValue>0:
  Schedule[m,t]=[c]

But since there's more than 1 c value for some m,t combinations, it doesnt work. I would like to have all the c values listed for the m,t combination.

Please help?

Use collections.defaultdict as Schedule , you can simply add c s to the list by:

from collections import defaultdict

schedule = defaultdict(list)
for (m,c,t) in mct:
    if Ymct[m][c][t].varValue>0:
    schedule[(m,t)].extend([c])

(As an aside, you should name your variables properly according to PEP8 . Specifically, use under_store for variable names and function names, and CapWords for class names)


Update:

To write a defaultdict to csv, you can consider the following approach: import csv

from collections import defaultdict

schedule = defaultdict(list)
schedule[1, 1] = [2, 3, 4]
schedule[1, 2] = [3, 4, 5]
schedule[1, 3] = [4, 5, 6]
schedule[1, 4] = [5, 6, 7]

with open("data.csv", "wb") as f:
    csv.writer(f).writerows([k, ] + v for k, v in schedule.iteritems())

Alternatively, I am wondering if LpVariable.varValue can return lists. And if so, the follwoing changes should work:

#schedule=defaultdict(list)
schedule = LpVariable.dicts("schedule", (moderator, time))

# ... many lines ...

for (m,c,t) in mct:
    if Ymct[m][c][t].varValue>0:
        #schedule[(m,t)].extend([c])
        schedule.setdefault(m, {}).setdefault(t, []).append(c)

# List entries in model output area
for (m,t) in mt:
    if len(schedule[(m,t)])>0:
        print (m,t), schedule[m][t]
        #print (m,t), schedule[(m,t)]

# ... many lines ...

for (m,t) in mt:
    timetable[m,t]=schedule[m][t].varValue
    #timetable[m,t]=schedule[m,t].items()

You can read over the changed code here: http://pastebin.com/UCVjqRwQ

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM