Gra*_*ale 3 arrays multidimensional-array julia
给定一个数组数组
x = [[1, 2, 3, 4], [4, 5, 6, 7]],
截断每个内部数组的干净有效的方法是什么,以便我最终得到
[[1, 2], [4, 5]]?
有没有x[:,1:2]像多维数组一样简单的东西?
您可以广播 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]
Run Code Online (Sandbox Code Playgroud)
它似乎比使用快一点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)
Run Code Online (Sandbox Code Playgroud)