【发布时间】:2021-08-17 15:54:48
【问题描述】:
例如,如果函数的输出(例如 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
【问题讨论】:
标签: arrays type-conversion julia