将值设置为字典数组中的特定元素会覆盖数组中的所有值

Kar*_*kel 3 dictionary julia

我正在尝试将特定值分配给字典数组中的特定位置。赋值覆盖数组中的所有值 - 为什么?

a = fill(Dict("example" => 0.),3)
a[1]["example"] = 1.
println(a)
Run Code Online (Sandbox Code Playgroud)

''' 输出是

[Dict("example" => 1.0), Dict("example" => 1.0), Dict("example" => 1.0)]
Run Code Online (Sandbox Code Playgroud)

gin*_*kul 5

这是 的预期行为,文档中fill对此进行了描述。

如果 x 是对象引用,则所有元素都将引用同一个对象

使用数组理解

我建议为此目的使用数组理解

julia> a = [Dict("example" => 0.) for _ in 1:3]
julia> a[1]["example"] = 1.                                                                                           
1.0
julia> println(a)
[Dict("example" => 1.0), Dict("example" => 0.0), Dict("example" => 0.0)]                                                                                                       
Run Code Online (Sandbox Code Playgroud)

替代map方案

如果你真的不喜欢列表推导式,你可以map通过实例化同一个字典的多个实例来实现相同的解决方案。

julia> b = map(x -> Dict("example" => 0.), 1:3)
3-element Vector{Dict{String, Float64}}:
 Dict("example" => 0.0)
 Dict("example" => 0.0)
 Dict("example" => 0.0)

julia> b[1]["example"] = 2.0
2.0

julia> println(b)
[Dict("example" => 2.0), Dict("example" => 0.0), Dict("example" => 0.0)]
Run Code Online (Sandbox Code Playgroud)