Fill an empty array (Vector of vectors) in Julia using for loop

Viewed 83

Given

b=[ [1,[2,3,7]], 
    [2,[7,2,7]],
    [3,[2,3,9]] ]

a=[ [2,3,7],[7,2,7],[2,3,9] ] 

I want to get b from empty vector of vectors using for loop.

b=[ [ ] ]
for i in 1:3
    b[i][1]=i
    b[i][2]=a[i]
end
2 Answers
julia> a = [[2,3,7],[7,2,7],[2,3,9]];

julia> b = enumerate(a) |> collect
3-element Vector{Tuple{Int64, Vector{Int64}}}:
 (1, [2, 3, 7])
 (2, [7, 2, 7])
 (3, [2, 3, 9])

As the output says, this returns a Vector of Tuples. If you do need exactly a vector of vectors for some reason, you can do:

julia> b = enumerate(a) |> collect .|> collect
3-element Vector{Vector{Any}}:
 [1, [2, 3, 7]]
 [2, [7, 2, 7]]
 [3, [2, 3, 9]]

For a tuple, just use tuple.(1:3,a), if a vector is required do vec.(1:3,a). Note that a tuple is an immutable container, so you might gain some performance benefits, and you can still change the elements of the vectors inside since vectors are mutable.

b = tuple.(1:3,a)
3-element Vector{Tuple{Int64, Vector{Int64}}}:
 (1, [2, 3, 7])
 (2, [7, 2, 7])
 (3, [2, 3, 9])

b = vec.(1:3,a)
3-element Vector{Vector{Any}}:
 [1, [2, 3, 7]]
 [2, [7, 2, 7]]
 [3, [2, 3, 9]]
Related