如何访问数组的最后一个元素?

Dav*_*ela 7 julia

我想访问某个数组的最后一个元素。

我正在使用length

last_element = x[length(x)]
Run Code Online (Sandbox Code Playgroud)

这样对吗?是否有一种规范的方式来访问 Julia 中有序集合的最后一个元素?

Dav*_*ela 12

length如果您的数组使用标准索引就可以了。但是,x[length(x)]如果数组使用自定义索引,则不一定返回最后一个元素。

更通用和明确的方法是使用last,无论索引方案如何,它都将返回数组的最后一个元素:

julia> x = rand(3)
3-element Array{Float64,1}:
 0.7633644675721114
 0.396645489023141 
 0.4086436862248366

julia> last(x)
0.4086436862248366
Run Code Online (Sandbox Code Playgroud)

如果您需要最后一个元素的索引,请使用lastindex

julia> lastindex(x)
3
Run Code Online (Sandbox Code Playgroud)

以下三种方法是等价的:

julia> last(x)
0.4086436862248366

julia> x[lastindex(x)]
0.4086436862248366

julia> x[end]
0.4086436862248366
Run Code Online (Sandbox Code Playgroud)

x[end]是 的语法糖x[lastindex(x)]

  • 还值得指出的是,“A[end]”只是“A[lastindex(A)]”的语法糖,它们是等效的。 (4认同)