420, -6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:47:55 25 4
gpt4 key购买 nike

如果我有两个向量:

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:
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
现在根据您的评论,我同意为什么 .=> 的原因可能不是很明显。有效:发生的事情是它创建了一个向量 Pair s:
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 中最好的事情之一,可以弄清楚发生了什么)

关于dictionary - 如何将 Julia 中的两个向量组合成一个字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65741581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com