Vectorized “in” function in julia?

前端 未结 5 1245
抹茶落季
抹茶落季 2020-11-28 13:53

I often want to loop over a long array or column of a dataframe, and for each item, see if it is a member of another array. Rather than doing

giant_list =          


        
5条回答
  •  心在旅途
    2020-11-28 14:19

    You can vectorize in quite easily in Julia v0.6, using the unified broadcasting syntax.

    julia> in.(giant_list, (good_letters,))
    3-element Array{Bool,1}:
      true
     false
     false
    

    Note the scalarification of good_letters by using a one-element tuple. Alternatively, you can use a Scalar type such as the one introduced in StaticArrays.jl.

    Julia v0.5 supports the same syntax, but requires a specialized function for scalarificiation (or the Scalar type mentioned earlier):

    scalar(x) = setindex!(Array{typeof(x)}(), x)
    

    after which

    julia> in.(giant_list, scalar(good_letters))
    3-element Array{Bool,1}:
      true
     false
     false
    

提交回复
热议问题