简体   繁体   English

Python 3.x在矩阵上得到奇数列

[英]Python 3.x get odd columns on matrix

I am working with python 3.7 and I would like to get all the odd columns of a matrix. 我正在使用python 3.7,我想获得矩阵的所有奇数列。

To give a example, I have a 4x4 matrix of this style right now. 举个例子,我现在有一个这种风格的4x4矩阵。

[[0, 9, 1, 6], [0, 3, 1, 5], [0, 2, 1, 7], [0, 6, 1, 2]]

That is... 那是...

0 9 1 6
0 3 1 5
0 2 1 7
0 6 1 2

And I would like to get: 我想得到:

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...], ...]

To get the rows I can do [:: 2] , but that wonderful solution does not work for me right now. 为了得到我可以做的行[:: 2] ,但这个奇妙的解决方案现在对我不起作用。 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? 我该如何解决?

Thank you. 谢谢。

Without using numpy , you can use something similar to your indexing scheme ( [1::2] ) in a list comprehension: 在不使用numpy ,您可以在列表numpy中使用类似于索引方案( [1::2] )的内容:

>>> [i[1::2] for i in mat]
[[9, 6], [3, 5], [2, 7], [6, 2]]

Using numpy , you can do something similar: 使用numpy ,你可以做类似的事情:

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

If you can't use NumPy for whatever reason, write a custom implementation: 如果由于某种原因无法使用NumPy,请编写自定义实现:

def getColumns(matrix, columns):
    return {c: [matrix[r][c] for r in range(len(matrix))] for c in columns}

It takes a 2D array and a list of columns, and it returns a dictionary where the column indexes are keys and the actual columns are values. 它采用2D数组和列列表,并返回一个字典,其中列索引是键,实际列是值。 Note that if you passed all indices you would get a transposed matrix. 请注意,如果您传递了所有索引,您将获得转置矩阵。 In your case, 在你的情况下,

M = [[0, 9, 1, 6],
    [0, 3, 1, 5],
    [0, 2, 1, 7], 
    [0, 6, 1, 2]]

All odd columns are even indices (because the index of the first one is 0), Therefore: 所有奇数列都是偶数索引 (因为第一的索引是0),因此:

L = list(range(0, len(M[0]), 2))

And then you would do: 然后你会这样做:

myColumns = getColumns(M, L)
print(list(myColumns.values()))
#result: [[0, 0, 0, 0], [1, 1, 1, 1]]

But since you showed the values as if they were in rows: 但是,因为您显示的值就像它们在行中一样:

def f(matrix, columns):
    return [[matrix[row][i] for i in columns] for row in range(len(matrix))]
print(f(M, L))
#result: [[0, 1], [0, 1], [0, 1], [0, 1]]

And I believe that the latter is what you wanted. 而且我相信后者就是你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM