Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding index of list based on another list in Julia

Tags:

list

julia

I have two lists, A and B, B the sublist of A. Both the elements in the A and B are randomly ordered. I am looking for a way to find indexes of elements in A for elements in B, probably ordered. In Python, the following seems to work

B_list = sorted([A.index(i) for i in B])

I am not sure how this can be achieved in Julia. I am pretty new to the Language. I tried something like

B_list = sort(filter(in(B), A))

It did not work at all, please help!

like image 274
stochastic learner Avatar asked Jan 25 '23 04:01

stochastic learner


1 Answers

There's a function (inspired by MATLAB) that can directly do it for you: indexin(B, A)

julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];
  
julia> b = ['a', 'b', 'c'];
  
julia> indexin(b, a)
3-element Vector{Union{Nothing, Int64}}:
 1
 2
 3

If you want the indices ordered, you can do a sort on that:

julia> b = ['b', 'a', 'c'];

julia> indexin(b, a)
3-element Vector{Union{Nothing, Int64}}:
 2
 1
 3

julia> indexin(b, a) |> sort
3-element Vector{Union{Nothing, Int64}}:
 1
 2
 3

like image 141
Sundar R Avatar answered Mar 04 '23 03:03

Sundar R