Python 3.x在矩阵上获取奇数列 [英] Python 3.x get odd columns on matrix
问题描述
我正在使用python 3.7,我想获取矩阵的所有奇数列.
I am working with python 3.7 and I would like to get all the odd columns of a matrix.
举个例子,我现在有一个这种样式的4x4矩阵.
To give a example, I have a 4x4 matrix of this style right now.
[[0, 9, 1, 6], [0, 3, 1, 5], [0, 2, 1, 7], [0, 6, 1, 2]]
那是...
0 9 1 6
0 3 1 5
0 2 1 7
0 6 1 2
我想得到:
9 6
3 5
2 7
6 2
矩阵的数字和大小会改变,但结构始终为
The numbers and the size of the matrix will change but the structure will always be
[[0, (int), 1, (int), 2...], [0, (int), 1, (int), 2 ...], [0, (int), 1, (int), 2...], [0, (int), 1, (int), 2...], ...]
要获取行,我可以执行 [:: 2]
,但是这种出色的解决方案目前对我不起作用.我尝试使用以下方法访问矩阵:
To get the rows I can do [:: 2]
, but that wonderful solution does not work for me right now. I try to access the matrix with:
for i in matrix:
for j in matrix:
但是,这一切都不起作用.我该怎么解决?
But none of this doesn't work either. How can I solve it?
谢谢.
推荐答案
如果不使用 numpy
,则可以使用类似于索引方案( [1 :: 2]
)中的列表理解:
Without using numpy
, you can use something similar to your indexing scheme ([1::2]
) in a list comprehension:
>>> [i[1::2] for i in mat]
[[9, 6], [3, 5], [2, 7], [6, 2]]
使用 numpy
,您可以执行类似的操作:
Using numpy
, you can do something similar:
>>> import numpy as np
>>> np.array(mat)[:,1::2]
array([[9, 6],
[3, 5],
[2, 7],
[6, 2]])
这篇关于Python 3.x在矩阵上获取奇数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!