Julia - 由另一个向量重复一个向量的条目(内部)

Phy*_*ent 5 julia

我有一个数组x,我想将每个条目重复x由另一个数组的相应条目指定的次数y,长度相同x

x = [1, 2, 3, 4, 5]    # Array to be repeated
y = [3, 2, 1, 2, 3]    # Repetitions for each element of x
# result should be [1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5]
Run Code Online (Sandbox Code Playgroud)

朱莉娅有办法做到这一点吗?

Cam*_*nek 4

你的xy向量构成了所谓的向量的游程编码[1, 1, 1, 2, 2, 3, 4, 4, 5, 5, 5]。因此,如果您采用游程编码的逆,您将得到您正在寻找的向量。StatsBase.jl包包含和函数我们可以这样使用:rleinverse_rleinverse_rle

julia> using StatsBase

julia> x = [1, 2, 3, 4, 5];

julia> y = [3, 2, 1, 2, 3];

julia> inverse_rle(x, y)
11-element Vector{Int64}:
 1
 1
 1
 2
 2
 3
 4
 4
 5
 5
 5
Run Code Online (Sandbox Code Playgroud)