如何将Julia中的两个向量组合成一个字典?

如果我有两个向量:

mykeys = ["a", "b", "c"]
myvals = [420, 69, 1337]

我怎样才能把它们变成一个对应对的字典,比如:

Dict("a" => 420, "b" => 69, "c" => 1337)

回答

广播的完美用例:

julia> Dict(mykeys .=> myvals)
Dict{String, Int64} with 3 entries:
  "c" => 1337
  "b" => 69
  "a" => 420

还有一个类似于 Python 的 Dict 理解:

julia> Dict((k, v) for (k, v) ? zip(mykeys, myvals))
Dict{String, Int64} with 3 entries:
  "c" => 1337
  "b" => 69
  "a" => 420

作为一般提示,通常当?SomeType你得到一个帮助条目,其中包括构造函数:

help?> Dict
search: Dict IdDict WeakKeyDict AbstractDict redirect_stdin redirect_stdout redirect_stderr isdispatchtuple to_indices parentindices LinearIndices CartesianIndices deuteranopic optimize_datetime_ticks DimensionMismatch

  Dict([itr])

  Dict{K,V}() constructs a hash table with keys of type K and values of type V. Keys are compared with isequal and hashed with hash.

  Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.

  Examples
  ??????????

  julia> Dict([("A", 1), ("B", 2)])
  Dict{String, Int64} with 2 entries:
    "B" => 2
    "A" => 1

  Alternatively, a sequence of pair arguments may be passed.

  julia> Dict("A"=>1, "B"=>2)
  Dict{String, Int64} with 2 entries:
    "B" => 2
    "A" => 1

另一个技巧是tab tab使用左括号键入构造函数并点击以获取 REPL 以显示您可以调用的方法:

julia> Dict(
Dict() in Base at dict.jl:118                               Dict(ps::Pair{K, V}...) where {K, V} in Base at dict.jl:124  Dict(kv) in Base at dict.jl:127
Dict(kv::Tuple{}) in Base at dict.jl:119                    Dict(ps::Pair...) in Base at dict.jl:125

现在根据你的评论,我同意它为什么.=>起作用可能不是很明显:发生的事情是它创建了一个Pairs向量:

julia> mykeys .=> myvals
3-element Vector{Pair{String, Int64}}:
 "a" => 420
 "b" => 69
 "c" => 1337

Dict()你问这个调用的哪个构造函数方法?

julia> x = mykeys .=> myvals;

julia> @which Dict(x)
Dict(kv) in Base at dict.jl:127

@which是 Julia 中最好的事情之一,可以弄清楚发生了什么)

  • Wow, I had no idea you could broadcast `=>`; that's amazing

以上是如何将Julia中的两个向量组合成一个字典?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>