来自 Julia 中的两个数组/向量的字典

Geo*_*ery 9 julia

如何Dict()从两个数组创建一个,一个带有键,一个带有值:

a = ["a", "b", "c"] # keys
b = [1,2,3]         # values
Run Code Online (Sandbox Code Playgroud)

Geo*_*ery 10

解决方案1

Dict(zip(a,b))
Run Code Online (Sandbox Code Playgroud)

解决方案2

Dict(a .=> b)
Run Code Online (Sandbox Code Playgroud)


Ant*_*llo 6

为了补充 Georgery 的答案,请注意,第一种方法 ( Dict(zip(a,b))) 对于小向量要快得多,但对于较大向量,差异可以忽略不计:

\n
julia> using BenchmarkTools\n\njulia> a = rand(5); b = rand(5);\n\njulia> @benchmark Dict(zip(a,b))\nBenchmarkTools.Trial: \n  memory estimate:  672 bytes\n  allocs estimate:  6\n  --------------\n  minimum time:     344.143 ns (0.00% GC)\n  median time:      356.382 ns (0.00% GC)\n  mean time:        383.371 ns (6.12% GC)\n  maximum time:     8.124 \xce\xbcs (94.84% GC)\n  --------------\n  samples:          10000\n  evals/sample:     217\n\njulia> @benchmark Dict(a .=> b)\nBenchmarkTools.Trial: \n  memory estimate:  832 bytes\n  allocs estimate:  7\n  --------------\n  minimum time:     950.615 ns (0.00% GC)\n  median time:      1.013 \xce\xbcs (0.00% GC)\n  mean time:        1.051 \xce\xbcs (2.30% GC)\n  maximum time:     62.573 \xce\xbcs (97.09% GC)\n  --------------\n  samples:          10000\n  evals/sample:     26\n\njulia> a = rand(50000);b = rand(50000);\n\njulia> @benchmark Dict(zip(a,b))\nBenchmarkTools.Trial: \n  memory estimate:  5.67 MiB\n  allocs estimate:  38\n  --------------\n  minimum time:     1.581 ms (0.00% GC)\n  median time:      1.611 ms (0.00% GC)\n  mean time:        1.675 ms (3.41% GC)\n  maximum time:     2.917 ms (25.30% GC)\n  --------------\n  samples:          2984\n  evals/sample:     1\n\njulia> @benchmark Dict(a .=> b)\nBenchmarkTools.Trial: \n  memory estimate:  6.43 MiB\n  allocs estimate:  40\n  --------------\n  minimum time:     1.624 ms (0.00% GC)\n  median time:      1.666 ms (0.00% GC)\n  mean time:        1.740 ms (3.79% GC)\n  maximum time:     3.762 ms (14.17% GC)\n  --------------\n  samples:          2873\n  evals/sample:     1\n
Run Code Online (Sandbox Code Playgroud)\n