Python 3.x 在矩阵上获取奇数列

Ash*_*Ash 4 python list python-3.x

我正在使用 python 3.7,我想获取矩阵的所有奇数列。

举个例子,我现在有一个这种风格的 4x4 矩阵。

[[0, 9, 1, 6], [0, 3, 1, 5], [0, 2, 1, 7], [0, 6, 1, 2]]
Run Code Online (Sandbox Code Playgroud)

那是...

0 9 1 6
0 3 1 5
0 2 1 7
0 6 1 2
Run Code Online (Sandbox Code Playgroud)

我想得到:

9 6
3 5
2 7
6 2
Run Code Online (Sandbox Code Playgroud)

矩阵的数量和大小会发生变化,但结构将始终不变

[[0, (int), 1, (int), 2...], [0, (int), 1, (int), 2 ...], [0, (int), 1, (int), 2...], [0, (int), 1, (int), 2...], ...]
Run Code Online (Sandbox Code Playgroud)

要获得我可以做的行[:: 2],但是这个绝妙的解决方案现在对我不起作用。我尝试使用以下方法访问矩阵:

for i in matrix:
    for j in matrix:
Run Code Online (Sandbox Code Playgroud)

但这一切都不起作用。我该如何解决?

谢谢你。

sac*_*cuL 6

不使用numpy,您可以[1::2]在列表推导式中使用类似于您的索引方案 ( ) 的内容:

>>> [i[1::2] for i in mat]
[[9, 6], [3, 5], [2, 7], [6, 2]]
Run Code Online (Sandbox Code Playgroud)

使用numpy,你可以做类似的事情:

>>> import numpy as np
>>> np.array(mat)[:,1::2]
array([[9, 6],
       [3, 5],
       [2, 7],
       [6, 2]])
Run Code Online (Sandbox Code Playgroud)