首页 > 解决方案 > 访问字典中的值时出现 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

不知道如何解决这个问题。

标签: juliajulia-jumpijulia-notebook

解决方案


您正在使用 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

推荐阅读