如何在 Julia 中查找数组中多个元素的位置

Lar*_*rry 3 arrays julia

这是我在 Julia 中的代码。我想在数组 a 中找到数组 b 元素的位置。

a = [2,4,1,3]
b = [1,4]
c=[]
for i in 1:length(b)
    push!(c, findfirst(isequal(b[i]), a));
end
println(c)
Run Code Online (Sandbox Code Playgroud)

结果是 [3, 2]。这是正确的。但我相信应该有一种更儒略(有效)的方法。我试过

julia> findall(x -> x == b, a)
0-element Array{Int64,1}
Run Code Online (Sandbox Code Playgroud)

这是错的。然后

julia> findall(x -> x == .b, a)
ERROR: syntax: invalid identifier name "."
Run Code Online (Sandbox Code Playgroud)

或者

julia> findall(x -> x .== b, a)
ERROR: TypeError: non-boolean (BitArray{1}) used in boolean context
Run Code Online (Sandbox Code Playgroud)

下面的结果是错误的!

julia> findall(x -> x in b, a)
2-element Array{Int64,1}:
 2
 3
Run Code Online (Sandbox Code Playgroud)

我认为它将 'b' 视为一个集合并忽略了 'b' 中的元素序列。我想要正确的序列 [3,2]。谁能帮我?谢谢。

fre*_*kre 6

您可以使用indexin

julia> a = [2,4,1,3]; b = [1,4];

julia> indexin(b, a)
2-element Array{Union{Nothing, Int64},1}:
 3
 2
Run Code Online (Sandbox Code Playgroud)

但是,不要for像第一个示例中那样害怕-loops,它们非常易读,并且通常与indexin.