将 n 元素 Vector{Vector{Int64}} 转换为 Vector{Int64}

Converting a n-element Vector{Vector{Int64}} to a Vector{Int64}

我有一个向量列表(向量的向量),如下所示:

A 2-element Vector{Vector{Int64}}: A= [347229118, 1954075737, 6542148346,347229123, 1954075753, 6542148341] [247492691, 247490813, -2796091443606465490, 247491615, 247492910, 247491620, -4267071114472318843, 747753505]

目标是将它们全部放在一个向量中。我确实尝试了 collectA[:]vec(A)flatten(A),但它仍然 returns 2-element Vector{Vector{Int64}} 我不知道我应该使用什么命令。有什么吗

假设您的输入数据是:

julia> x = [[1, 2], [3, 4], [5, 6]]
3-element Vector{Vector{Int64}}:
 [1, 2]
 [3, 4]
 [5, 6]

这里有一些自然选择。

选项 1:使用 Iterators.flatten:

julia> collect(Iterators.flatten(x))
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

您可以省略 collect,在这种情况下,您会得到一个对源数据的惰性迭代器,它的内存效率更高。

选项 2:使用 vcat:

julia> reduce(vcat, x)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

你也可以这样写:

julia> vcat(x...)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

但如果您的 x 向量很长,则展开可能会出现问题。在这种情况下,我建议您使用 reduce 函数,如上所示。