将数组提升到最后一个索引的通用方法:包括所有索引

时间:2022-12-11 23:30:55

I have an index i running that indicates how to slice a particular array a. For example,

我有一个运行的索引,指示如何切片特定的数组a。例如,

a = np.arange(10)
for i in np.arange(1, 5):
    print(a[i:], a[:-i])

Output

[1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8]
[2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7]
[3 4 5 6 7 8 9] [0 1 2 3 4 5 6]
[4 5 6 7 8 9] [0 1 2 3 4 5]

However, this will not work for i=0:

但是,这对i = 0不起作用:

a[0:]
Out[67]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[:-0]
Out[68]: array([], dtype=int64)

Where my expected / required output would have been

我的预期/要求输出的位置

a[0:]
Out[67]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
a[:-0]
Out[67]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

What is the reason for this asymmetry? Ultimately, I need to

这种不对称的原因是什么?最终,我需要

  • select less and less from either end
  • 从任何一端选择越来越少

  • Corner case: Select only one from each end (which I can do generically via a[i:] and a[:-i], when i==9
  • 转角案例:从每一端只选择一个(当我= = 9时,我可以通过[i:]和[: - i]进行一般操作

  • Corner case: Select all from both ends (which will not work, given that a[:-0] returns not the expected result.
  • 转角案例:从两端选择全部(如果[: - 0]不返回预期结果,则无效)。

How can I achieve this?

我怎样才能做到这一点?

1 个解决方案

#1


3  

Because -0 is 0 (at least in the integer domain where the most popular representation is 2-complement) and the unary minus is evaluated first. For floating points there are two representations for -0 and 0, but usually a programming language makes abstraction o that.

因为-0是0(至少在最流行的表示是2补码的整数域中)并且首先计算一元减号。对于浮点,有两个表示-0和0,但通常编程语言会对其进行抽象。

You can however use None in that case, so you can write it as:

但是,在这种情况下,您可以使用None,因此您可以将其写为:

a = np.arange(10)
for i in np.arange(0,10):
    print(a[i:], a[:-i or None])

For i=0, this returns:

对于i = 0,返回:

[0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9]

#1


3  

Because -0 is 0 (at least in the integer domain where the most popular representation is 2-complement) and the unary minus is evaluated first. For floating points there are two representations for -0 and 0, but usually a programming language makes abstraction o that.

因为-0是0(至少在最流行的表示是2补码的整数域中)并且首先计算一元减号。对于浮点,有两个表示-0和0,但通常编程语言会对其进行抽象。

You can however use None in that case, so you can write it as:

但是,在这种情况下,您可以使用None,因此您可以将其写为:

a = np.arange(10)
for i in np.arange(0,10):
    print(a[i:], a[:-i or None])

For i=0, this returns:

对于i = 0,返回:

[0 1 2 3 4 5 6 7 8 9] [0 1 2 3 4 5 6 7 8 9]