数组和向量之间的区别 [英] Difference between Array and Vector
问题描述
Array
和Vector
之间是否有区别?
typeof(Array([1,2,3]))
Vector{Int64}
typeof(Vector([1,2,3]))
Vector{Int64}
两者似乎都可以创建相同的东西,但是它们并不相同:
Both seem to create the same thing, but they are not the same:
Array == Vector
false
Array === Vector
false
那么,实际上有什么区别?
So, what is actually the difference?
推荐答案
区别在于Vector
是一维Array
,因此当您编写例如Vector{Int}
这是Array{Int, 1}
的简写:
The difference is that Vector
is a 1-dimensional Array
, so when you write e.g. Vector{Int}
it is a shorthand to Array{Int, 1}
:
julia> Vector{Int}
Array{Int64,1}
当您调用构造函数Array([1,2,3])
和Vector([1,2,3])
时,在向其传递向量时,它们会在内部转换为相同的调用Array{Int,1}([1,2,3])
.
When you call constructors Array([1,2,3])
and Vector([1,2,3])
they internally get translated to the same call Array{Int,1}([1,2,3])
as you passed a vector to them.
如果要传递非一维数组,您会看到不同之处:
You would see the difference if you wanted to pass an array that is not 1-dimensional:
julia> Array(ones(2,2))
2×2 Array{Float64,2}:
1.0 1.0
1.0 1.0
julia> Vector(ones(2,2))
ERROR: MethodError: no method matching Array{T,1} where T(::Array{Float64,2})
还要注意以下效果:
julia> x=[1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> Vector(x)
3-element Array{Int64,1}:
1
2
3
julia> Vector(x) === x
false
因此,呼叫Vector(x)
本质上是x
的副本.通常,在代码中,您可能只写copy(x)
.
So essentially the call Vector(x)
makes a copy of x
. Usually in the code you would probably simply write copy(x)
.
一般规则是Array
是参数类型,具有用花括号括起来的两个参数:
A general rule is that Array
is a parametric type that has two parameters given in curly braces:
- 第一个是元素类型(您可以使用
eltype
进行访问) - 第二个是数组的维数(您可以使用
ndims
访问它)
- the first one is element type (you can access it using
eltype
) - the second one is the dimension of the array (you can access it using
ndims
)
请参阅 https://docs.julialang.org/en/v1/manual /arrays/了解详情.
这篇关于数组和向量之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!