julia - 访问字典中的值时出现 Julia 键错误
问题描述
在尝试运行此代码时,只要我尝试访问需求 [i],Julia 就会不断给我错误消息“KeyError: key 18=>63 not found”。似乎每次 dem 中的元素大于 50 时都会发生此错误。
using JuMP, Clp
hours = 1:24
dem = [43 40 36 36 35 38 41 46 49 48 47 47 48 46 45 47 50 63 75 75 72 66 57 50]
demand = Dict(zip(hours, dem))
m = Model(solver=ClpSolver())
@variable(m, x[demand] >= 0)
@variable(m, y[demand] >= 0)
for i in demand
if demand[i] > 50
@constraint(m, y[i] == demand[i])
else
@constraint(m, x[i] == demand[i])
end
end
不知道如何解决这个问题。
解决方案
您正在使用 Python 风格的for x in dict
. 在 Julia 中,这会迭代字典的键值对,而不是键。尝试
for i in keys(demand)
if demand[i] > 50
@constraint(m, y[i] == demand[i])
else
@constraint(m, x[i] == demand[i])
end
end
或者
for (h, d) in demand
if d > 50
@constraint(m, y[h] == d)
else
@constraint(m, x[h] == d)
end
end
推荐阅读
- python - 按级别提取嵌套列表中的字符串
- python - 运行机器人文件的命令,我也可以在其中指定 python 版本
- c++ - 随机数未达到限制
- javascript - 使用 fs 模块更改 node.js 中的 html 页面文件
- html - 按钮文本颜色没有改变
- android - 数组字符串到 Int android
- autodesk-forge - Autodesk Forge 查看器在加载其他文档时出错
- javascript - 为什么这个简单的 AngularJS ng-show 不能显示子列表?
- java - 如何在 Java 中传递带参数的方法引用?
- android - 在 Retrofit Api 请求中使用密码套件有什么好处?