当数组中没有任何内容时,如何从数组 eltype 中删除 Nothing?
How to remove Nothing from an array eltype when there are no nothing in the array?
例如,如果函数的输出(例如 indexin
)具有 Vector{Union{Nothing, Int64}}
类型,
但事先知道只会输出值(没有nothing
)。
这个输出应该被提供给另一个函数
对于这种类型来说这是错误的,但是对于简单的 Int64
.
数组来说很好
说
julia> output = Union{Nothing, Int64}[1, 2] # in practice, that would be output from a function
2-element Vector{Union{Nothing, Int64}}:
1
2
如何将该输出转换为 Int64
的数组?
下面的方法适用于这种情况,可以聚集在一个函数中,但必须有更优雅的方式。
julia> subtypes = Base.uniontypes(eltype(output))
2-element Vector{Any}:
Nothing
Int64
julia> no_Nothing = filter(!=(Nothing), subtypes)
1-element Vector{Any}:
Int64
julia> new_eltype = Union{no_Nothing...}
Int64
julia> Array{new_eltype}(output)
2-element Vector{Int64}:
1
2
尝试 something
:
julia> output = Union{Nothing, Int64}[1, 2]
2-element Vector{Union{Nothing, Int64}}:
1
2
julia> something.(output)
2-element Vector{Int64}:
1
2
例如,如果函数的输出(例如 indexin
)具有 Vector{Union{Nothing, Int64}}
类型,
但事先知道只会输出值(没有nothing
)。
这个输出应该被提供给另一个函数
对于这种类型来说这是错误的,但是对于简单的 Int64
.
说
julia> output = Union{Nothing, Int64}[1, 2] # in practice, that would be output from a function
2-element Vector{Union{Nothing, Int64}}:
1
2
如何将该输出转换为 Int64
的数组?
下面的方法适用于这种情况,可以聚集在一个函数中,但必须有更优雅的方式。
julia> subtypes = Base.uniontypes(eltype(output))
2-element Vector{Any}:
Nothing
Int64
julia> no_Nothing = filter(!=(Nothing), subtypes)
1-element Vector{Any}:
Int64
julia> new_eltype = Union{no_Nothing...}
Int64
julia> Array{new_eltype}(output)
2-element Vector{Int64}:
1
2
尝试 something
:
julia> output = Union{Nothing, Int64}[1, 2]
2-element Vector{Union{Nothing, Int64}}:
1
2
julia> something.(output)
2-element Vector{Int64}:
1
2