给定一个数组数组
x = [[1, 2, 3, 4], [4, 5, 6, 7]]
,
什么是截断每个内部数组的简洁有效的方法,以便我最终得到
[[1, 2], [4, 5]]
?
有没有像 x[:,1:2]
这样简单的多维数组?
最佳答案
您可以broadcast 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)
关于arrays - Julia 截断数组数组的内部维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60106041/