在朱莉娅解压缩一系列元组

Ead*_*hey 9 julia

假设我有一个元组数组:

arr = [(1,2), (3,4), (5,6)]
Run Code Online (Sandbox Code Playgroud)

用python我可以做到 zip(*arr) == [(1, 3, 5), (2, 4, 6)]

在朱莉娅中,这相当于什么?

nic*_*y12 9

您可以使用zip()函数(此处为docs)在Julia中实现相同的功能.zip()期望使用许多元组,因此您必须使用splatting运算符 ...来提供参数.同样在Julia中,您必须使用该collect()函数然后将迭代变换为数组(如果您愿意).

以下是这些功能的实际应用:

arr = [(1,2), (3,4), (5,6)]

# wtihout splatting
collect(zip((1,2), (3,4), (5,6)))

# Output is a vector of arrays:
> ((1,3,5), (2,4,6))

# same results with splatting
collect(zip(arr...))
> ((1,3,5), (2,4,6))
Run Code Online (Sandbox Code Playgroud)

  • 请注意,对于大型数组,这非常慢!见 https://github.com/JuliaLang/julia/issues/13930#issuecomment-155142306 (3认同)

ivi*_*hup 8

作为 splatting 的替代方案(因为这很慢),您可以执行以下操作:

unzip(a) = map(x->getfield.(a, x), fieldnames(eltype(a)))
Run Code Online (Sandbox Code Playgroud)

这相当快。

julia> using BenchmarkTools
julia> a = collect(zip(1:10000, 10000:-1:1));
julia> @benchmark unzip(a)
BenchmarkTools.Trial: 
  memory estimate:  156.45 KiB
  allocs estimate:  6
  --------------
  minimum time:     25.260 ?s (0.00% GC)
  median time:      31.997 ?s (0.00% GC)
  mean time:        48.429 ?s (25.03% GC)
  maximum time:     36.130 ms (98.67% GC)
  --------------
  samples:          10000
  evals/sample:     1
Run Code Online (Sandbox Code Playgroud)

相比之下,我还没有看到这个完整的:

@time collect(zip(a...))
Run Code Online (Sandbox Code Playgroud)

  • 我可以确认这个答案中的“unzip”函数比“zip”函数快 10 倍以上,而且使用的内存也少得多。我使用的是运行 Julia 1.1 的 Mac。 (2认同)