访问字典中的值时出现 Julia Key 错误

Julia Key Error when accessing a value in dictionary

当尝试 运行 这段代码时,每当我尝试访问 demand[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

这对我有用,使用 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))

参考文献:

  1. @Fengyang Wang 回复
  2. @Wikunia 在
  3. 的评论
  4. https://jump.readthedocs.io/en/latest/quickstart.html