Is there a Julia equivalent to NumPy's ellipsis slicing syntax (…)?

こ雲淡風輕ζ 提交于 2019-12-05 03:29:05

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

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.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!