在 Python 中切片 3d 数组列表

los*_*und 3 multidimensional-array python-3.x

我刚从 MATLAB 进入 python3。所以我的问题可能很愚蠢,虽然我仔细研究了这个问题,但找不到解决我的问题的方法。所以这是我的问题 - 我使用创建了一个 3d 数组列表

routine_matrix = [[[0 for k in range(xaxis)] for j in range(yaxis)] for i in range(zaxis)]
routine_matrix[0][0][1] = 'aa'
routine_matrix[1][0][1] = 'bb'
routine_matrix[2][0][1] = 'cc'
routine_matrix[3][0][1] = 'dd'
routine_matrix[4][0][1] = 'ee'
routine_matrix[0][1][1] = 'ff'
routine_matrix[0][2][1] = 'gg'
Run Code Online (Sandbox Code Playgroud)

这就是 3d 列表的样子:

[[[0, 'aa', 0, 0], [0, 'ff', 0, 0], [0, 'gg', 0, 0]],
 [[0, 'bb', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 'cc', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 'dd', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
 [[0, 'ee', 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Run Code Online (Sandbox Code Playgroud)

现在,如果我想访问元素“aa”、“bb”、“cc”、“dd”和“ee”,使用 for 循环,我可以使用以下代码轻松实现:

for i in range(0,5):
    print(routine_matrix[i][0][1])
Run Code Online (Sandbox Code Playgroud)

但是,我想要做的是,我想一次性从 3d 列表中切片 - 类似于:

print(routine_matrix[0:,0,1])
Run Code Online (Sandbox Code Playgroud)

但是,我没有得到我想要的输出。所以我要问的是如何一次性切掉“aa”、“bb”、“cc”、“dd”和“ee”。

谢谢你的时间!

Arp*_*wal 5

也许你想出了答案,但无论如何这里是我的答案:

在 3d 数组中,切片语法由 [矩阵、行、列] 表示

import numpy as np

# Below we are creating a 3D matrix similar to your matrix where there are 
# 5 matrices each containing 3 rows and 4 columns

routine_matrix = np.arange(5*3*4).reshape((5,3,4))
print(routine_matrix) 
Run Code Online (Sandbox Code Playgroud)

例程_矩阵:

[[[ 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]]

 [[36 37 38 39]
  [40 41 42 43]
  [44 45 46 47]]

 [[48 49 50 51]
  [52 53 54 55]
  [56 57 58 59]]]
Run Code Online (Sandbox Code Playgroud)

现在,根据您的问题,您对 1, 13, 25, 37, 49 感兴趣,它是每个内部矩阵的第 0 行和第 1 列的第一个元素

所以,为了实现我们所做的

print(routine_matrix[:, 0, 1])
Run Code Online (Sandbox Code Playgroud)

在这里了解切片:

  • ':' 表示选择所有矩阵
  • '0' 表示只选择所有矩阵的第 0 行

即: [0 1 2 3], [12, 13, 14, 15], [24, 25, 26, 27], [36, 37, 38, 39], [48, 49, 50, 51]

  • '1' 表示在上面选择的所有行中只选择第一列(数组索引在 python 中从 0 开始)

即: [1, 13, 25, 37, 49]

因此输出:

[ 1 13 25 37 49]
Run Code Online (Sandbox Code Playgroud)

在您的情况下,它将是 ['aa' 'bb' 'cc' 'dd' 'ee']