问题
In NumPy, the ellipsis syntax is for
filling in a number of
:
until the number of slicing specifiers matches the dimension of the array.
(paraphrasing this answer).
How can I do that in Julia?
回答1:
Not yet, but you can help yourself if you want.
import Base.getindex, Base.setindex!
const .. = Val{:...}
setindex!{T}(A::AbstractArray{T,1}, x, ::Type{Val{:...}}, n) = A[n] = x
setindex!{T}(A::AbstractArray{T,2}, x, ::Type{Val{:...}}, n) = A[ :, n] = x
setindex!{T}(A::AbstractArray{T,3}, x, ::Type{Val{:...}}, n) = A[ :, :, n] =x
getindex{T}(A::AbstractArray{T,1}, ::Type{Val{:...}}, n) = A[n]
getindex{T}(A::AbstractArray{T,2}, ::Type{Val{:...}}, n) = A[ :, n]
getindex{T}(A::AbstractArray{T,3}, ::Type{Val{:...}}, n) = A[ :, :, n]
Then you can write
> rand(3,3,3)[.., 1]
3x3 Array{Float64,2}:
0.0750793 0.490528 0.273044
0.470398 0.461376 0.01372
0.311559 0.879684 0.531157
If you want more elaborate slicing, you need to generate/expand the definition or use staged functions.
Edit: Nowadays, see https://github.com/ChrisRackauckas/EllipsisNotation.jl
回答2:
They way to go is EllipsisNotation.jl, which adds ..
to the language.
Example:
julia> using EllipsisNotation
julia> x = rand(1,2,3,4,5);
julia> x[..,3] == x[:,:,:,:,3]
true
julia> x[1,..] == x[1,:,:,:,:]
true
julia> x[1,1,..] == x[1,1,:,:,:]
true
(@mschauer noted this his answer (edit) already, but the reference is at the very end, and I felt this question deserved a clean up-to-date answer.)
来源:https://stackoverflow.com/questions/30159815/is-there-a-julia-equivalent-to-numpys-ellipsis-slicing-syntax