numpy - 元组不是 numpy 中的“(...)”?

numpy - tuple is not "(...)" in numpy?

我对元组的理解是可以用括号括起来

Tuples may be constructed in a number of ways:

Using a pair of parentheses to denote the empty tuple: ()
Using a trailing comma for a singleton tuple: a, or (a,)
Separating items with commas: a, b, c or (a, b, c)
Using the tuple() built-in: tuple() or tuple(iterable)

Basic Slicing and Indexing 表示切片索引是切片对象和整数的元组。

Basic slicing occurs when obj is a slice object (constructed by start:stop:step notation inside of brackets), an integer, or a tuple of slice objects and integers.

但是,(...)不能使用导致错误。错误来自numpy还是Python?

我想没有括号,0:1, 2:3, 1 仍然是一个元组,但是如果指定为 a tuple of slice objects and integers 为什么不能使用括号?

它不是那么重要,但在与 numpy 索引斗争之后,这让它变得更加混乱,因此澄清会有所帮助。

Z = np.arange(36).reshape(3, 3, 4)
print("Z is \n{}\n".format(Z))

a = Z[
    (0:1, 2:3, 1)
]
---
  File "<ipython-input-53-26b1604433cd>", line 5
    (0:1, 2:3, 1)
      ^
SyntaxError: invalid syntax

这有效。

Z = np.arange(36).reshape(3, 3, 4)
print("Z is \n{}\n".format(Z))

a = Z[
    0:1, 2:3, 1
]
print(a)
print(a.base is not None)

根据 hpaulj 的评论,numpy s_ 内部采用“切片和整数列表”和 returns 切片对象的元组。

from numpy import s_
print(s_[0:1, 2:3, 1])

Z = np.arange(36).reshape(3, 3, 4)
print("Z is \n{}\n".format(Z))

print(Z[s_[0:1, 2:3, 1]])
---
(slice(0, 1, None), slice(2, 3, None), 1)
Z is 
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]

 [[24 25 26 27]
  [28 29 30 31]
  [32 33 34 35]]]

[[9]]

1:2这样的切片符号是语法,它不会创建对象,所以你不能在列表或元组或任何东西中使用它们;另一方面,slice objects 实际上指的是 slice() 返回的东西,它们的行为相同,这就是 Numpy 所引用的“切片对象和整数元组”。执行您期望的操作的有效语法是 Z[(slice(1, 2), slice(2, 3), 1)]。这允许您将切片保存到一个变量并使用它们。

这里有一个简单的代码片段来演示:

>>> 1:2
  File "<stdin>", line 1
SyntaxError: illegal target for annotation
>>> slice(1, 2)
slice(1, 2, None)
>>> [1, 2, 3][1:2]
[2]
>>> [1, 2, 3][slice(1, 2)]
[2]