例如,如果函数的输出(例如 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
最佳答案
尝试一些东西
:
julia> output = Union{Nothing, Int64}[1, 2]
2-element Vector{Union{Nothing, Int64}}:
1
2
julia> something.(output)
2-element Vector{Int64}:
1
2
关于arrays - 当数组中没有任何内容时,如何从数组 eltype 中删除 Nothing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67755153/