Как выполнить добавление списка словарей в python? - PullRequest
0 голосов
/ 04 мая 2018

При попытке выполнить эту операцию я получаю следующую ошибку:

prob1 += sum([x[d][s]*Dic_Trancosts[d][s] for (d,s) in routes]) #add the DC cost
**TypeError**: string indices must be integers

Подскажите, пожалуйста, что не так?

dcCap=[30, 30, 40, 70]
dcCost=[700, 800, 1600, 800]
customerDemand=[40, 30, 40]
transcostlist_of_lists=[[4, 16, 8, 4], 
[6, 6, 6, 9], 
[12, 15, 7, 8]]
DClist=['S1', 'S2', 'S3', 'S4']
Demandlist=['D1', 'D2', 'D3'] 
import pulp
from pulp import *
# The supply capacity data is made into a dictionary
Dic_DCCapacity = makeDict([DClist], dcCap,0) #default 0 if no data entry is 
found
Dic_DCCapacity
# The fixed cost of each DC is made into a dictionary
Dic_DCCost = makeDict([DClist], dcCost,0)
Dic_DCCost
# The demand data is made into a dictionary
Dic_Demand = makeDict([Demandlist], customerDemand,0)
Dic_Demand
# The cost data is made into a dictionary
Dic_Trancosts = makeDict([Demandlist,DClist], transcostlist_of_lists,0)
Dic_Trancosts

prob1 = LpProblem("Network Design Problem1", LpMinimize)
#Each pair of (Demandlist,DClist) is associated with a decision variable, 
#indicating the flow between DC and customer

#Decision variable (binary) that is associated with whether or not to open a DC  

routes = [(d,s) for d in Demandlist for s in DClist]
routes

prob1 += sum([x[d][s]*Dic_Trancosts[d][s] for (d,s) in routes]) \
#add the DC cost


# Supply maximum constraints are added to prob for each supply node (DC)

for s in DClist:
prob1 += sum([x[d][s] for d in Demandlist]) <= Dic_DCCapacity[s]

# Demand minimum constraints are added to prob for each demand node (bar)

# Write out the lp file to you directory

1 Ответ

0 голосов
/ 04 мая 2018

немного трудно сказать без примера, но эта ошибка

TypeError: string indices must be integers

В целом означает, что вы пытаетесь проиндексировать строку с помощью чего-то отличного от intiger:

>>> s = "my string"
>>> s[1]
'y'
>>> s["y"]

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    s["y"]
TypeError: string indices must be integers, not str

Мое лучшее предположение состоит в том, что x - это строка, а не словарь, и когда вы пытаетесь проиндексировать ее с помощью x[d][s], где d и s - строки, Python выдает ошибку.

Не уверен, что x должно быть в вашем коде, но я бы начал искать там

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...