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

例如,如果函数的输出(例如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

  • `something` in this case works, but in general it would unwrap `Some` if it were present in the array so it is not ideal. A general approach to automatic `eltype` narrowing AFAICT is to call `identity.(output)` or just `[v for v in output]`.

以上是当数组中没有任何内容时,如何从数组eltype中删除Nothing?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>