【问题标题】:How to remove Nothing from an array eltype when there are no nothing in the array?当数组中没有任何内容时,如何从数组 eltype 中删除 Nothing?
【发布时间】: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


    【解决方案1】:

    试试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
    

    【讨论】:

    • 或者,您可以使用Int.(output) 强制Int 类型。这是使用 Julia 的广播语法将 Int 的“构造函数”应用于向量的所有条目。
    • something 在这种情况下有效,但通常如果 Some 存在于数组中,它会解开它,所以它并不理想。自动缩小 AFAICT eltype 的一般方法是调用 identity.(output) 或直接调用 [v for v in output]
    • 我认为如果在这里看到nothing 会出错。如果您愿意,可以使用something.(output, 0) 明确提供在这种情况下应该提供的内容。
    • 在问题中明确指出“预先知道只会输出值”。因此我给出了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    相关资源
    最近更新 更多