从元组向量到向量元组

时间:2017-08-28 13:48:17

标签: arrays tuples julia

在Julia中,很多东西都表示为小元组的数组,例如(++) s。但有时你会喜欢这些元素分开,例如提取用于绘图的x和y坐标 - 例如有一个数组元组。您可以部分使用Point

zip

虽然你可以

,但这会导致一个元组元组
pts = [(1,2), (1,3), (2,3), (2,2)]
a,b = collect(zip(pts...))

有没有更方便的方法来执行此操作?

1 个答案:

答案 0 :(得分:3)

由Tim Holy提供,有MappedArray包。有了它,以下对于眼睛和处理器来说都很容易:

julia> using MappedArrays

julia> struct Point
       x::Float64
       y::Float64
       end

julia> pvec = [Point(rand(),rand()) for i=1:10];

julia> b = mappedarray(e->e.x,pvec);

julia> b[3]
0.9524214421389912

julia> b
10-element MappedArrays.ReadonlyMappedArray{Float64,1,Array{Point,1},##3#4}:
 0.383683
 0.474853
 0.952421
 0.388564
 0.268427
 0.301026
 0.117767
 0.712266
 0.629364
 0.227822

与往常一样,应该明确衡量性能,但如果内容正确内联,则应该没问题。

更新

对于元组的向量,它将是mappedarray(e->first(e),tvec)和变体。例如:

julia> tvec = [(rand(),rand()) for i=1:10000];

julia> c = mappedarray(x->first(x),tvec);

julia> c[5]
0.8626336507168362

而且结果是sum(c)很快:

julia> @btime sum(first.(tvec))
  21.643 μs (25 allocations: 79.23 KiB)
5000.93749585252

julia> @btime sum(c)
  9.850 μs (1 allocation: 16 bytes)
5000.937495852521

julia> @btime sum(first(x) for x in tvec)
  10.560 μs (2 allocations: 32 bytes)
5000.937495852521
相关问题