如何在 Julia 中模仿数组的 Pythonic 索引

How to imitate Pythonic indexing of arrays in Julia

我正在将 Python 中的代码翻译成 Julia。我有以下数组:

_DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

以及以下代码行:

_DAYS_IN_MONTH[index] - _DAYS_IN_MONTH[index - 1]

想法是,如果 index - 1 的计算结果为 -1,那么我们将获得数组的最后一个元素,这正是我们在本例中所需要的。但是,这在 Julia 中不起作用。当然,我可以这样写:

if index == 1
    _DAYS_IN_MONTH[index] - _DAYS_IN_MONTH[end]
else
    _DAYS_IN_MONTH[index] - _DAYS_IN_MONTH[index - 1]
end

但我想知道是否有更优雅和“Julian”的方式来做到这一点。

实际上,您所追求的是 . You achieve that with mod1 的一个非常具体的案例。它会“环绕”有效索引之外的值。它需要两个参数;第一个是值(要换行的索引),第二个是模数(数组的长度)。在索引的上下文中,您可以只使用特殊的 end 语法作为模数:

julia> [_DAYS_IN_MONTH[index] - _DAYS_IN_MONTH[mod1(index - 1, end)] for index in 1:12]
12-element Vector{Int64}:
  0
 -3
  3
 -1
  1
 -1
  1
  0
 -1
  1
 -1
  1

另一个优雅的选择是using CircularArrays

julia> _DAYS_IN_MONTH = CircularVector([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]);

julia> _DAYS_IN_MONTH .- _DAYS_IN_MONTH[0:end-1]
12-element CircularVector(::Vector{Int64}):
  0
 -3
  3
 -1
  1
 -1
  1
  0
 -1
  1
 -1
  1

using ShiftedArrays:

julia> _DAYS_IN_MONTH .- circshift(_DAYS_IN_MONTH,1)
12-element Vector{Int64}:
  0
 -3
  3
 -1
  1
 -1
  1
  0
 -1
  1
 -1
  1

不需要额外的包,Julia Base 有这个:

_DAYS_IN_MONTH .- circshift(_DAYS_IN_MONTH,1)