问题:是否有 Julia 等效于 NumPy 的省略号切片语法 (...)?

在 NumPy 中,省略号语法用于

填写:个数,直到切片说明符的个数与数组的维度相匹配。

(解释这个答案)。

我怎么能在 Julia 中做到这一点?

解答

还没有,但如果你愿意,你可以帮助自己。

    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]

然后你可以写

    > 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

如果您想要更精细的切片,则需要生成/扩展定义或使用分段函数。

编辑:如今,请参阅https://github.com/ChrisRackauckas/EllipsisNotation.jl

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐