首页 > 解决方案 > Julia 截断数组数组的内部维度

问题描述

给定一个数组数组

x = [[1, 2, 3, 4], [4, 5, 6, 7]],

什么是截断每个内部数组的干净有效的方法,以便我最终得到

[[1, 2], [4, 5]]?

有没有x[:,1:2]像多维数组一样简单的东西?

标签: arraysmultidimensional-arrayjulia

解决方案


你可以广播 getindex

julia> x = [[1, 2, 3, 4], [5, 6, 7, 8]];

julia> getindex.(x, (1:2,))
2-element Array{Array{Int64,1},1}:
 [1, 2]
 [5, 6]

它似乎比使用快一点map

julia> foo(xs) = getindex.(xs, (1:2,))
foo (generic function with 1 method)

julia> bar(xs) = map(x -> x[1:2], xs)
bar (generic function with 1 method)

julia> @btime foo($([rand(1000) for _ in 1:1000]));
  55.558 μs (1001 allocations: 101.69 KiB)

julia> @btime bar($([rand(1000) for _ in 1:1000]));
  58.841 μs (1002 allocations: 101.70 KiB)

推荐阅读