user9990604
user9990604

Reputation:

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

I have a list of vectors (vector of vectors) like the following:

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

the goal is to have them all in just one vector. I did try collect, A[:], vec(A), flatten(A) but it still returns 2-element Vector{Vector{Int64}} I don't know what command I should use. Is there anything

Upvotes: 1

Views: 824

Answers (1)

Bogumił Kamiński
Bogumił Kamiński

Reputation: 69819

Assuming your input data is:

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

here are some natural options you have.

Option 1: use Iterators.flatten:

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

You can omit collect in which case you get a lazy iterator over the source data which is more memory efficient.

Option 2: use vcat:

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

You could also write:

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

but splatting might get problematic if your x vector is very long. In which case I recommend you to use the reduce function as shown above.

Upvotes: 2

Related Questions