在Julia中基于另一个列表查找列表的索引。

4

我有两个列表A和B,其中B是A的子列表。A和B中的元素都是随机排序的。 我想找到一种方法来查找A中与B中相应元素的索引,可能是有序的。在Python中,下面的代码似乎可以实现此功能:

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

我不确定在Julia语言中如何实现这一点。我对这门语言相当陌生。我尝试了类似于下面的代码:

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

完全没有作用,请帮助!

2个回答

6

有一个函数(灵感来自MATLAB),可以直接为您完成此操作: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


如果你希望索引有序,你可以对它们进行排序:
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


2
您可以尝试这种理解式的方法。
# 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]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接