首页 > 解决方案 > 在 julia 中正确创建数组数组

问题描述

我想在 julia 中用整数填充数组。以下作品:

a = Array{Int64}[]
push!(a, [1,2,3])

但这不是:

a = Array{Array{Int64}}[]
push!(a, [1, 2, 3])

错误是:MethodError: Cannot `convert` an object of type Int64 to an object of type Array{Int64,N} where N

有人可以解释为什么吗?似乎Array{Array{Int64}}应该是数组的类型,其元素是包含 Int64 值Array{Int64}的数组,而是整数数组。然而a = Array{Int64}[]似乎初始化了一个包含整数的数组而不是一个整数数组?有人可以澄清这里的逻辑吗?

标签: arraysjulia

解决方案


a = Array{Int64}[]
push!(a, [1,2,3])

是一个数组向量,在操作之后你有一个包含一个数组的 1 元素向量:

julia> a
1-element Array{Array{Int64,N} where N,1}:
 [1, 2, 3]

julia> a[1]
3-element Array{Int64,1}:
 1
 2
 3

尽管:

a = Array{Array{Int64}}[]

为您创建一个数组数组的向量:

julia> a = Array{Array{Int64}}[]
0-element Array{Array{Array{Int64,N} where N,N} where N,1}

所以你可以push!进入它的数组数组,例如:

julia>     push!(a, [[1,2,3]])
1-element Array{Array{Array{Int64,N} where N,N} where N,1}:
 [[1, 2, 3]]

julia> a[1]
1-element Array{Array{Int64,N} where N,1}:
 [1, 2, 3]

julia> a[1][1]
3-element Array{Int64,1}:
 1
 2
 3

推荐阅读