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

标签 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

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

相关文章:

julia - 在 Julia 中获取嵌套数组的形状

c - 实现元胞自动机? "Rule 110"

c# - 在不知道数组大小的情况下从 C 到 C# P/Invoke

php - 了解 PHP $GLOBALS 变量

ruby - 日期、日期时间和时区

optimization - 打印IPOPT参数

statistics - 如何从此函数获得一致的返回类型?

arrays - 将数组中的每个单词大写

c++ - 使用模板编译错误 - 没有匹配的调用函数

c# - 从C#中的列表中选择指定的子类型