gpt4 book ai didi

python - (i :j:k) numpy slicing?) 中 j 的默认值是多少

转载 作者:太空狗 更新时间:2023-10-30 00:06:38 25 4
gpt4 key购买 nike

我一直在阅读 numpy i:j:k 切片的教程 Scipy.org .在第二个例子之后,它说

Assume n is the number of elements in the dimension being sliced. Then, if i is not given it defaults to 0 for k > 0 and n - 1 for k < 0. If j is not given it defaults to n for k > 0 and -1 for k < 0. If k is not given it defaults to 1.

但是:

>>> import numpy as np
>>> x = np.array([0,1,2,3,4])
>>> x[::-1]
array([4, 3, 2, 1, 0])

如果 j 默认为 -1,那么 x[:-1:-1] 应该等同于 x[::-1],但是

>>> x[:-1:-1]
array([], dtype=int64)
>>> x[:-(len(x)+1):-1]
array([4, 3, 2, 1, 0])

同时

>>> x[:-(len(x)+1):-1]
array([4, 3, 2, 1, 0])

所以当k < 0j的默认值应该是-(n+1)。并根据this post on stackoverflow ,我相信 k < 0j 的“官方”默认值是 None

我是否误解了 SciPy.org 上的教程?

最佳答案

在第一级处理中,Python 解释器将 :: 转换为符号为 slice目的。这取决于 numpy.__getitem__解释这 3 个数字的方法。

[::-1]slice(None,None,-1)相同.

如您所见,x[slice(None,None,-1)]x[slice(None,-1,-1)] 不同.

我怀疑 -1在:

If j is not given it defaults to n for k > 0 and -1 for k < 0 .

不应该以这种方式使用。相反,它具有 -1 的通常含义,the number before 0 .

在 [285] 中:np.arange(10)[slice(5,0,-1)] Out[285]: 数组([5, 4, 3, 2, 1])

j被解释为 iterate upto, but not including, this value , 迭代方向由 k 决定.所以 0值不包含在此切片中。

那么如何包含 0

In [287]: np.arange(10)[slice(5,-1,-1)]
Out[287]: array([], dtype=int32)

不起作用,因为 -1理解为 n-1 ,如:

In [289]: np.arange(10)[slice(5,-7,-1)]
Out[289]: array([5, 4])

None以一种特殊的方式解释,让我们可以使用:

In [286]: np.arange(10)[slice(5,None,-1)]
Out[286]: array([5, 4, 3, 2, 1, 0])

这也有效( 10-11=-1 - 真正的 -1 )

In [291]: np.arange(10)[slice(5,-11,-1)]
Out[291]: array([5, 4, 3, 2, 1, 0])

所以-1之间是有区别的这意味着 before 0 , 和 -1这意味着 count from n .文档可能对此很清楚,但这并没有错(如果您使用正确的 -1)。

关于python - (i :j:k) numpy slicing?) 中 j 的默认值是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31145413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com