当数组中没有任何内容时,如何从数组 eltype 中删除 Nothing?

ede*_*rag 3 arrays type-conversion julia

例如,如果函数的输出(例如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
Run Code Online (Sandbox Code Playgroud)

如何将该输出转换为数组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

Run Code Online (Sandbox Code Playgroud)

Prz*_*fel 5

尝试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
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,“something”是有效的,但一般来说,如果“Some”存在于数组中,它会解开它,因此它并不理想。自动“eltype”缩小 AFAICT 的一般方法是调用“identity.(output)”或只是“[v for v in output]”。 (2认同)