问题
In python this would be something like:
Z = []
z = 1
Z.append([z])
which would create Z= [[1]]
for example. But in Julia, I cannot seem to re-create the same structure. I can append, but don't know how to nest. Here is what I am doing in summary:
Z = []
# loop
z = dotProduct(X, yArray) # single digit
append!(Z, z)
which then generates the following
0Any[0, 0, 0, 0, 1, 1, 1, 1]
where as I would like:
[[0], [0], [0], [0], [1], [1], [1], [1]]
What is the best way to do this in Julia?
回答1:
The only way I found to make this work was the following:
Z = Array{Int64,1}[]
push!(Z, [1])
push!(Z, [2])
print(Z)
giving
Array{Int64,1}[[1], [2]]
Not very elegant, but I cannot seem to get this working without the Array keyword.
回答2:
Like this perhaps?
julia> Z = Array{Array{Int64,1},1}[]
0-element Array{Array{Array{Int64,1},1},1}
julia> push!(Z, [[1]])
1-element Array{Array{Array{Int64,1},1},1}:
[[1]]
julia> push!(Z, [[2]])
2-element Array{Array{Array{Int64,1},1},1}:
[[1]]
[[2]]
julia> push!(Z[1], [3])
2-element Array{Array{Int64,1},1}:
[1]
[3]
julia> Z
2-element Array{Array{Array{Int64,1},1},1}:
[[1], [3]]
[[2]]
来源:https://stackoverflow.com/questions/53741949/nested-append-to-an-array-in-julia