给定一个二维数组:
如何高效地截取每个内部数组,以便最终获得以下结果:
是否有类似于多维数组的
x = [[1, 2, 3, 4], [4, 5, 6, 7]]
,如何高效地截取每个内部数组,以便最终获得以下结果:
[[1, 2], [4, 5]]
?是否有类似于多维数组的
x[:,1:2]
这样简单的方法?x = [[1, 2, 3, 4], [4, 5, 6, 7]]
,[[1, 2], [4, 5]]
?x[:,1:2]
这样简单的方法?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)
resize!.(x, 2)
这个函数会在原地改变x
,所以你不需要为它分配一个输出变量。
你也可以使用view
。这不会改变输入,但也不会分配新的向量。它比广播的getindex
快,但比resize!
慢:
xv = view.(x, Ref(1:2))
Ref
的用法吗? - Grayscalex
的元素上广播,而不是在1:2
上广播。Ref
使其表现得像一个标量。 - DNF