我想在Julia中找到一种简洁的语法,以向量化的方式索引字典。在R中,我将执行以下操作:
dict <- c("a" = 1, "b" = 2)
keys <- c("a", "a", "b", "b", "a")
dict[keys]
Run Code Online (Sandbox Code Playgroud)
在茱莉亚,如果我有一个dict和keys这样的
dict = Dict(:a => 1, :b => 2)
keys = [:a, :a, :b, :b, :a]
Run Code Online (Sandbox Code Playgroud)
那么我可以使用列表理解来达到预期的结果:
julia> [dict[key] for key in keys]
5-element Array{Int64,1}:
1
1
2
2
1
Run Code Online (Sandbox Code Playgroud)
是否有更简洁的矢量化语法,类似于R语法?
您可以使用矢量化版本getindex:
julia> getindex.([dict], keys)
5-element Array{Int64,1}:
1
1
2
2
1
Run Code Online (Sandbox Code Playgroud)
请注意,它dict被包装在一个数组中,这样就getindex不会尝试广播字典的元素:
julia> getindex.(dict, keys)
ERROR: ArgumentError: broadcasting over dictionaries and `NamedTuple`s is reserved
Stacktrace:
[1] broadcastable(::Dict{Symbol,Int64}) at ./broadcast.jl:615
[2] broadcasted(::Function, ::Dict{Symbol,Int64}, ::Array{Symbol,1}) at ./broadcast.jl:1164
[3] top-level scope at none:0
Run Code Online (Sandbox Code Playgroud)