2

我有一个关于 python 的简单问题。我不想遍历 3D 的第一行ndarray,而是想选择整个列。所以让我们说:而不是:

print test[0][20][33]
print test[1][20][33]
...

我想放一些类似的东西:

 print test[:][20][33]

但这不起作用。我该怎么做?

4

1 回答 1

5

Put all the terms inside the square brackets:

>>> import numpy as np
>>> v = np.array(np.arange(24)).reshape(2,3,4)
>>> v
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11]],

       [[12, 13, 14, 15],
        [16, 17, 18, 19],
        [20, 21, 22, 23]]])
>>> v[:, 1, 3]
array([ 7, 19])

.. although I'm not sure I'd call that the first column. You can easily shuffle the indices to get whatever you're after, though:

>>> v[0, :, 0]
array([0, 4, 8])
>>> v[1, 1, :]
array([16, 17, 18, 19])

[relevant doc section on indexing]

于 2012-09-02T15:54:19.937 回答