【问题标题】:Julia Key Error when accessing a value in dictionary访问字典中的值时出现 Julia 键错误
【发布时间】:2018-10-06 04:29:19
【问题描述】:

当我尝试运行此代码时,Julia 在我尝试访问需求 [i] 的任何时候都会不断给我错误消息“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

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

【问题讨论】:

    标签: julia julia-jump ijulia-notebook


    【解决方案1】:

    您正在使用 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 索引 JuMPArray 失败:18 ∉ Dict(18=>63,2=>40,16=>47,11= >47,21=>72,7=>41,9=>49,10=>48,19=>75,17=>50,8=>46,22=>66,6=>38,24= >50,4=>36,3=>36,5=>35,20=>75,23=>57,13=>48,14=>46,15=>45,12=>47,1= >43)”出现了。我之前在使用字典之前尝试迭代数组时收到了类似的消息。
    • 正如 hesham_EE 在他们的回答中提到的,您还需要使用键迭代器而不是字典本身来构造您的 JuMP 数组。 (行@variable(m, x[demand] >= 0)
    【解决方案2】:

    这对我有用,使用 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 在https://stackoverflow.com/a/51910619/1096140 上的评论
    3. https://jump.readthedocs.io/en/latest/quickstart.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 2017-01-06
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多