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!
CodePudding user response:
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
CodePudding user response:
You can also try this comprehension-style way
# data
julia> show(A)
[9, 7, 4, 7, 8, 3, 1, 10, 4, 10]
julia> show(B)
[10, 8, 3, 7]
julia> sort([A[findall(i.==A)] for i in B])
4-element Vector{Vector{Int64}}:
[3]
[7, 7]
[8]
[10, 10]
