如何在python中执行字典添加列表?

2024-10-05 14:26:50 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试执行此操作时,出现以下错误:

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

Tags: oftheinfordataisdccost
1条回答
网友
1楼 · 发布于 2024-10-05 14:26:50

没有例子有点难说,但这个错误

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]索引它时,ds是字符串,Python会抛出一个错误。你知道吗

我不确定你的代码中应该有什么x,但我会从那里开始寻找

相关问题 更多 >