You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中字典列表加法实现及TypeError报错排查求助

Fixing TypeError: string indices must be integers in Your Pulp Optimization Code

Let's break down this error and fix it step by step. The issue occurs in this line:

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

The error means you're trying to use a string (like 'D1' or 'S1') to index a sequence that only accepts integer indices (e.g., a list) or a dictionary whose keys are integers, not strings.

Root Causes & Fixes

1. Your x variable uses integer keys instead of strings

If you defined x using integer ranges (e.g., range(len(Demandlist))), it will only accept integer indices. But your routes likely contain string values from Demandlist and DClist (like ('D1', 'S1')), leading to a mismatch.

Fix: Define x with string keys matching your customer and DC names:

# Correct variable definition using Demandlist/DClist strings as keys
x = LpVariable.dicts("Transport", (Demandlist, DClist), lowBound=0, cat='Continuous')

2. Dic_Trancosts isn't properly mapped to string keys

Your transcostlist_of_lists is a 2D list with integer indices, but Dic_Trancosts needs to use the string names from Demandlist and DClist as keys to match x and routes.

Fix: Build Dic_Trancosts as a nested dictionary with string keys:

Dic_Trancosts = {}
for d_idx, customer in enumerate(Demandlist):
    Dic_Trancosts[customer] = {}
    for s_idx, dc in enumerate(DClist):
        Dic_Trancosts[customer][dc] = transcostlist_of_lists[d_idx][s_idx]

Now Dic_Trancosts['D1']['S1'] correctly returns 4, matching your cost list.

3. Ensure routes contains string tuples

Double-check that routes is constructed using the string values from Demandlist and DClist, not integers:

# Correct route list with string pairs
routes = [(d, s) for d in Demandlist for s in DClist]

Full Working Code Snippet

import pulp
from pulp import *

# Original variable definitions
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']

# Build properly keyed transport cost dictionary
Dic_Trancosts = {}
for d_idx, customer in enumerate(Demandlist):
    Dic_Trancosts[customer] = {dc: transcostlist_of_lists[d_idx][s_idx] for s_idx, dc in enumerate(DClist)}

# Initialize LP problem
prob1 = LpProblem("Distribution_Problem", LpMinimize)

# Define transport variables with string keys
x = LpVariable.dicts("Transport", (Demandlist, DClist), lowBound=0, cat='Continuous')

# Define valid routes (string tuples)
routes = [(d, s) for d in Demandlist for s in DClist]

# Add transport cost objective (no more TypeError!)
prob1 += sum([x[d][s] * Dic_Trancosts[d][s] for (d, s) in routes]), "Total_Transport_Cost"

# Optional: Add remaining constraints (DC capacity, customer demand)
# DC Capacity Constraints
for s_idx, dc in enumerate(DClist):
    prob1 += sum([x[d][dc] for d in Demandlist]) <= dcCap[s_idx], f"DC_Capacity_{dc}"

# Customer Demand Constraints
for d_idx, customer in enumerate(Demandlist):
    prob1 += sum([x[customer][s] for s in DClist]) >= customerDemand[d_idx], f"Customer_Demand_{customer}"

内容的提问来源于stack exchange,提问作者Himanshu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:03:30