【问题标题】:Find element in an array that is of a particular type in Julia在 Julia 中查找特定类型的数组中的元素
【发布时间】:2019-04-16 00:50:50
【问题描述】:

我想在 Julia 中使用一个函数(我确定有一个),它接受一个数组(或类似类型)和一个类型(例如空)作为输入,检查数组中的每个元素以查看是否element 属于该类型,并返回 Array 中属于该类型的元素的索引。例如:

    typeToFind = nothing
    A = [1,2,3,nothing,5]
    idx = find(x->x == typeToFind,A)

基本上类似于 MATLAB。我发现了一些使用 find 的建议,但似乎已被弃用 - 当我尝试使用它时,Julia 会抱怨。我认为 Julia 中一定有这种功能,尽管我当然可以编写一些非常快速的代码来完成上述工作。

【问题讨论】:

    标签: arrays julia


    【解决方案1】:

    findfindall 取代,所以你应该试试:

    julia> findall(x->typeof(x)==Nothing, A)
    
    ## which returns:
    1-element Array{Int64,1}:
    4
    
    julia> findall(x->typeof(x)==Nothing, A)
    
    ## which returns:
    4-element Array{Int64,1}:
    1
    2
    3
    5
    

    【讨论】:

      【解决方案2】:

      使用findall(x->typeof(x)==Nothing, A) 可以解决问题,但对于某些类型T 使用x->isa(x, T) 可能会更好。原因是typeof(x) 不适用于抽象类型,因为typeof(x) 总是返回具体类型。

      这是一个用例:

      A = Any[1,UInt8(2),3.1,nothing,Int32(5)]
      
      findall(x->isa(x, Int), A)
      1-element Array{Int64,1}:
       1
      
      findall(x->isa(x, UInt8), A)
      1-element Array{Int64,1}:
       2
      
      findall(x->isa(x, Integer), A)  # Integer is an abstract type
      3-element Array{Int64,1}:
       1
       2
       5
      
      findall(x->typeof(x)==Integer, A)
      0-element Array{Int64,1}   # <- Doesn't work!
      

      它似乎也更快:

      julia> @btime findall(x->typeof(x)==Nothing, $A)
        356.794 ns (6 allocations: 272 bytes)
      1-element Array{Int64,1}:
       4
      
      julia> @btime findall(x->isa(x, Nothing), $A)
        120.255 ns (6 allocations: 272 bytes)
      1-element Array{Int64,1}:
       4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多