如何从 Julia 中的最后一个元素中获取第二个元素

How to get the second element from the last in Julia

在 Julia 中有什么方法可以做到这一点吗?

#Python
lst = [1, 2, 3]
print(lst[-2]) # prints out 2

我知道 last 函数获取最后一个,但我想从最后一个获取第二个。

谢谢!!

在数组索引的上下文中,end 可以用作表示数组最后一个索引的特殊语法,无论它是什么。所以 lst[end-1] 就是您要找的。

julia> lst = [1, 2, 3];

julia> lst[end-1]
2

您可能想查看 Julia 的 "Noteworthy Differences from Other Languages" 页面的 Python 部分。该页面的一些相关注释:

  • Julia does not support negative indices. In particular, the last element of a list or array is indexed with end in Julia, not -1 as in Python.
  • Julia requires end for indexing until the last element. x[1:] in Python is equivalent to x[2:end] in Julia.