Nested append to an Array in Julia

微笑、不失礼 提交于 2021-02-08 06:53:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!