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

Django+PuLP运输问题WebApp开发:NameError报错求助

解决运输问题代码中的NameError和TypeError问题

先帮你搞定眼前的NameError——这确实是个容易疏忽的小错误,咱们看这段仓库约束的代码:

for x in Warehouses:
    prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x

这里有两个明显的问题:

  • 内层列表推导式里你用了x作为循环变量,直接覆盖了外层循环的x(也就是当前遍历的仓库),逻辑完全乱了;
  • 变量y根本没在推导式里定义过,Python自然会报它未赋值的错误。

正确的写法应该是,对每个仓库x,遍历所有分销商y,计算从x到每个y的运输量之和:

for x in Warehouses:
    prob += lpSum([route_vars[x][y] for y in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x

同样的,你的分销商约束代码也犯了一模一样的错误:

for y in Distributors:
    prob += lpSum([route_vars[x][y] for y in Warehouses]) >= demand[y], "Sum of Products into Distributors %s"%y

这里内层循环用y覆盖了外层的y,而且x没定义,正确的写法应该是遍历仓库x:

for y in Distributors:
    prob += lpSum([route_vars[x][y] for x in Warehouses]) >= demand[y], "Sum of Products into Distributors %s"%y

再说说你之前遇到的TypeError——当用字符串命名Warehouses和Distributors时(比如Warehouses = ["A", "B", "C"]),出现list indices must be integers or slices, not str的错误,原因是你的costs是二维列表,只能用整数索引,但你却用字符串(比如"A")去索引它了。

解决这个问题的办法是把costs改成字典结构,和supply、demand的键类型保持一致,比如:

Warehouses = ["A", "B", "C"]
supply = {"A": deliver1, "B": deliver2, "C": deliver3}
Distributors = ["D", "E", "F"]
demand = {"D": receiver1, "E": receiver2, "F": receiver3}
costs = {
    "A": {"D":3, "E":5, "F":7},
    "B": {"D":12, "E":10, "F":9},
    "C": {"D":13, "E":3, "F":9},
}

这样后续用costs[x][y]的时候,不管x和y是字符串还是数字,都能正常索引了。

最后把修正后的完整核心代码贴出来,方便你参考:

Warehouses = [0,1,2]
supply = { 0: deliver1, 1: deliver2, 2: deliver3 }
Distributors = [0, 1, 2]
demand = { 0: receiver1, 1: receiver2, 2: receiver3 }
costs = [ 
    [3, 5, 7],#A Warehouse
    [12, 10, 9],#B Warehouse
    [13, 3, 9],#C Warehouse
]
prob = LpProblem("Transportation Problem",LpMinimize)
Routes = [(x,y) for x in Warehouses for y in Distributors]
route_vars = LpVariable.dicts("Route",(Warehouses,Distributors),0,None,LpInteger)

# 目标函数
prob += lpSum([route_vars[x][y]*costs[x][y] for (x,y) in Routes]), "Sum of Transporting Costs"

# 仓库供应约束(已修正)
for x in Warehouses:
    prob += lpSum([route_vars[x][y] for y in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x

# 分销商需求约束(已修正)
for y in Distributors:
    prob += lpSum([route_vars[x][y] for x in Warehouses]) >= demand[y], "Sum of Products into Distributors %s"%y

prob.writeLP("TransportationProblem.lp")
prob.solve()
print("Status:", LpStatus[prob.status])
for v in prob.variables():
    print(v.name, "=", v.varValue)
print("Total Cost of transportation = ", value(prob.objective))

内容的提问来源于stack exchange,提问作者Marcin Mirzyński

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 15:02:33