ilo*_*cp3 4 dictionary tuples julia
朱莉娅的新手,很困惑.
这是一个数组:
array=["a","b",1]
Run Code Online (Sandbox Code Playgroud)
我定义了一本字典
dict=Dict()
dict["a","b"]=1
Run Code Online (Sandbox Code Playgroud)
我想用'array'来定义dict
dict2 = Dict()
dict2[array[1:2]]=1
Run Code Online (Sandbox Code Playgroud)
但他们不一样,
julia> dict
Dict{Any,Any} with 1 entry:
("a","b") => 1
julia> dict2
Dict{Any,Any} with 1 entry:
Any["a","b"] => 1
Run Code Online (Sandbox Code Playgroud)
如何使用'array'生成'dict'而不是'dict2'?谢谢
您可以在执行任务时使用splat运算符:
julia> dict = Dict()
Dict{Any,Any} with 0 entries
julia> dict[array[1:2]...] = 1
1
julia> dict
Dict{Any,Any} with 1 entry:
("a","b") => 1
Run Code Online (Sandbox Code Playgroud)
注意:您可以在Dict中指定类型,这样可以防止这些类型的错误:
dict = Dict{Tuple{String, String}, Int}()
Run Code Online (Sandbox Code Playgroud)
Julia解释像dict["a", "b"] = 1as dict[("a", "b")] = 1这样的东西,即多维键被解释为元组键.
问题出现是因为输出array[1:2]不是元组而是数组.您可以将数组转换为元组
tup = tuple(array[1:2]...)
Run Code Online (Sandbox Code Playgroud)
然后你可以
dict2 = Dict()
dict2[tup] = 1
Run Code Online (Sandbox Code Playgroud)
请注意使用splat运算符...解压缩array[1:2]以创建一个2元素元组,而不是在不使用时创建的1元素元组(其唯一元素是2元素数组)....