简体   繁体   中英

SolverStudio how to reference 1 column in a 2D list in a for loop(PuLP)

I have 2 data sets x1 and x2. I want to be able to get a total sum of all the products of x1 and x2 only in the rows where the From column has Auckland in it. see here

The final answer should be (5*1) + (2*1) + (3*1) + (4*1) or 14. The PuLP code that I wrote to do this is given below

# Import PuLP modeller functions
from pulp import *

varFinal = sum([x1[a] * x2[a] for a in Arcs if a == Nodes[0]])

print Nodes[0]
print Arcs[0]

Final = varFinal

The output that gets printed to the console is

Auckland
('Auckland', 'Albany')

I realise that my final value is zero because Arcs[some number] does not equal Nodes[some number]. Is there anyway to change the code so my final value is 14?

Any help is appreciated.

Welcome to stack overflow! Cause you've only posted part of your code, I have to guess at what data-types you're using. From the output, I'm guessing your Nodes are strings, and your Arcs are tuples of strings.

Your attempt is very close, you want the from column to have Auckland in it. You can index into a tuple the same way you would into an array, so you want to do: a[0] == Nodes[0] .

Below is a self-contained example with the first bit of your data in which outputs the following (note that I've changed to python 3.x print statements (with parentheses)):

Output:

Auckland
('Auckland', 'Albany')
14

Code:

# Import PuLP modeller functions
from pulp import *

# Data
Nodes = ['Auckland',
        'Wellington',
        'Hamilton',
        'Kansas City',
        'Christchuch',
        'Albany',
        'Whangarei',
        'Rotorua',
        'New Plymouth']

Arcs = [('Auckland','Albany'),
        ('Auckland','Hamilton'),
        ('Auckland','Kansas City'),
        ('Auckland','Christchuch'),
        ('Wellington','Hamilton'),
        ('Hamilton','Albany'),
        ('Kansas City','Whangarei'),
        ('Christchuch','Rotorua')]

x1_vals = [1, 2, 3, 4, 5, 9, 11, 13]
x2_vals = [5, 1, 1, 1, 1, 1, 1, 1]

x1 = dict((Arcs[i], x1_vals[i]) for i in range(len(Arcs)))
x2 = dict((Arcs[i], x2_vals[i]) for i in range(len(Arcs)))

varFinal = sum([x1[a] * x2[a] for a in Arcs if a[0] == Nodes[0]])

print(Nodes[0])
print(Arcs[0])
print(varFinal)

For future reference, answers are most likely to be forthcoming if you include code which others can try to run (without external data dependencies), that way people can try to run it, fix it, and re-post it.

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