简体   繁体   English

在python中打印矩阵的右对角线值

[英]Print right diagonal values of a matrix in python

I have a 5 x 5 matrix of integers, and need to use certain code in Python. 我有一个5 x 5的整数矩阵,需要在Python中使用某些代码。 I need to construct a list containing the values in the cells on the diagonal from top-right to bottom-left of matrix. 我需要构造一个列表,其中包含矩阵从右上角到左下角的对角线上的单元格中的值。

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

Desired output: 所需的输出:

[5, 9, 13, 17, 21]

Partial code attempt: 尝试部分代码:

diagonal = []
for posi in matrix???:
    diagonal.append(??? ???)

Given that you want the diagonal from the upper right to the bottom left, you need matrix positions [(0, n), (1, n-1), ..., (n-1, 1), (n, 0)]. 假设您想要从右上角到左下角的对角线,则需要矩阵位置[[0,n),(1,n-1),...,(n-1,1),(n,0 )]。 The first value of each pair is easily obtained using range(len(matrix)) . 使用range(len(matrix))可以轻松获得每对的第一个值。 The second value can be obtained by subtracting the first value (ie the row number) from the length or width of the square matrix (and then subtracting one more due to zero based indexing). 可以通过从方矩阵的长度或宽度中减去第一个值(即行号)(然后由于基于零的索引而再减去一个)来获得第二个值。 Now you just look up each row/column tuple pair to get the index. 现在,您只需查找每个行/列元组对以获取索引。

diagonal = []
for row in range(len(matrix)):
    col = len(matrix) - row - 1  # zero based indexing
    diagonal.append(matrix[row][col])

>>> diagonal
[5, 9, 13, 17, 21]

I would suggest using the corresponding numpy classes, in this case numpy.matrix . 我建议使用相应的numpy类,在这种情况下为numpy.matrix Numpy then allows us to flip values from left to right and extract the diagonal. 然后,Numpy允许我们从左向右翻转值并提取对角线。

import numpy as np

mymatrix = np.matrix([[ 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]])

mydiagonal = np.matrix.diagonal(np.fliplr(mymatrix))

print(mydiagonal)
[[ 5  9 13 17 21]]

If the output has to be a list, it's easy to convert using tolist() : 如果输出必须是列表,则可以使用tolist()轻松进行转换:

print(mydiagonal.tolist()[0])
[5, 9, 13, 17, 21]

many code for easy thing 许多简单的代码

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

#this mode is faster
matrix=[matrix[c][d] for c in xrange(5) for d in xrange(5)]
print matrix

matrix=[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] 矩阵= [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]

#then we work better
print'Result',matrix[4:-1:4]

Result [5, 9, 13, 17, 21] 结果[5,9,13,17,21]

#and the asc diagonal
print'Result',matrix[::6]

Result [1, 7, 13, 19, 25] 结果[1、7、13、19、25]

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

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