Julia: Check if elements from one vector are within another vector [duplicate]

微笑、不失礼 提交于 2020-02-25 04:41:12

问题


I would like to check if the elements in one vector are contained within another vector. In R there is the operator %in%.

For example the operator would do the following:

 [1,3,5,7,9,4] %in% [1,2,4,5,8,9,10,11] 
 # [true,false,true,false,true,true]

I can easily write my own only I am trying not to reinvent the wheel.


回答1:


There are a number of built-ins that do something similar. indexin gives you the indices in b where the elements of a are found (0 if it is not there - this is similar to R's match). setdiff gives you the elements in a that are not in b. It is likely you'll be able to do what you want with these - constructing temporary boolean arrays for filtering is not so ideomatic in julia as in R, as it generally creates an extra, unnecessary allocation.




回答2:


Probably not so nice, but you could do:

julia> [1,3,5,7,9,4] .∈ [[1,2,4,5,8,9,10,11]]
6-element BitArray{1}:
  true
 false
  true
 false
  true
  true



回答3:


You could use an anonymous function : map(x -> x in [1,2,4,5,8,9,10,11] ,[1,3,5,7,9,4])
Or a comprehension : [x in [1,2,4,5,8,9,10,11] for x = [1,3,5,7,9,4]]



来源:https://stackoverflow.com/questions/46411683/julia-check-if-elements-from-one-vector-are-within-another-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!