访问字典中的值时,Julia键错误

时间:2018-10-06 04:29:20

标签: julia julia-jump ijulia-notebook

在尝试运行此代码时,Julia每次尝试访问需求[i]时,都会不断向我显示错误消息“ KeyError:键18 => 63找不到”。似乎每当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

不确定如何解决此问题。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这对我有效,使用了Julia 1.0

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()
setsolver(m, ClpSolver())

@variable(m, x[keys(demand)] >= 0)
@variable(m, y[keys(demand)] >= 0)

for (h, d) in demand
    if d > 50
        @constraint(m, y[h] == d)
    else
        @constraint(m, x[h] == d)
    end
end

status = solve(m)

println("Objective value: ", getobjectivevalue(m))
println("x = ", getvalue(x))
println("y = ", getvalue(y))

REF:

  1. @王凤阳的回信
  2. @Wikunia在https://stackoverflow.com/a/51910619/1096140的评论
  3. https://jump.readthedocs.io/en/latest/quickstart.html