Julia DefaultDict为每个键使用相同的值(数组)

时间:2018-10-05 09:35:42

标签: data-structures julia defaultdict

我想创建一个数组的defaultdict。问题是,每个键都使用相同的数组。

# using Pkg
# Pkg.add("DataStructures")
using DataStructures: DefaultDict
genome = DefaultDict{Tuple{String, String}, Array{Int64, 1}}(Int64[])
push!(genome["chr1", "+"], 5)
# 1-element Array{Int64,1}:
# 5

push!(genome["chrX", "-"], 10)
# 2-element Array{Int64,1}:
#  5
# 10

我尝试向其输入lambda来创建新数组x -> Int64,但这只是产生类型错误。

2 个答案:

答案 0 :(得分:2)

我不知道如何使用DefaultDict解决您的问题,但我认为Julia的内置字典结构提供了更好的解决方案。一个可以使用

get!(collection, key, default)

自动提供尚未设置的默认值。 上面的代码将被重写:

genome = Dict{Tuple{String, String}, Array{Int64, 1}}()
push!(get!(genome, ("chr1", "+"), Int64[]), 5)
# 1-element Array{Int64,1}:
# 5

push!(get!(genome, ("chrX", "-"), Int64[]), 10)
# 1-element Array{Int64,1}:
# 10

答案 1 :(得分:2)

如果从字面上使用x -> Int64,则没有任何意义:您的initiiliazer不需要参数,它应该返回值,而不是类型。您可能想使用的是() -> Int64[]

julia> genome = DefaultDict{Tuple{String, String}, Array{Int64, 1}}(() -> Int64[])
DefaultDict{Tuple{String,String},Array{Int64,1},getfield(Main, Symbol("##7#8"))} with 0 entries

julia> genome["a", "b"]
0-element Array{Int64,1}

julia> push!(genome["a", "c"], 5)
1-element Array{Int64,1}:
 5

julia> genome
DefaultDict{Tuple{String,String},Array{Int64,1},getfield(Main, Symbol("##7#8"))} with 2 entries:
  ("a", "c") => [5]
  ("a", "b") => Int64[]

julia> push!(genome["a", "b"], 4)
1-element Array{Int64,1}:
 4

julia> genome
DefaultDict{Tuple{String,String},Array{Int64,1},getfield(Main, Symbol("##7#8"))} with 2 entries:
  ("a", "c") => [5]
  ("a", "b") => [4]

如果要基于尝试的键创建默认值,则可以将passkey = true与以该键作为参数的初始化函数一起使用;有关所有选项,请参见the docs