假设我有一个元组数组:
arr = [(1,2), (3,4), (5,6)]
Run Code Online (Sandbox Code Playgroud)
用python我可以做到 zip(*arr) == [(1, 3, 5), (2, 4, 6)]
在朱莉娅中,这相当于什么?
您可以使用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)
作为 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)
| 归档时间: |
|
| 查看次数: |
1970 次 |
| 最近记录: |