我有一个5 x 5的整数矩阵,需要在Python中使用某些代码。 我需要构建一个列表,其中包含矩阵右上角到左下角对角线单元格中的值。
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]]
期望的输出:
[5, 9, 13, 17, 21]
部分代码尝试:
diagonal = []
for posi in matrix???:
diagonal.append(??? ???)
答案 0 :(得分:1)
鉴于您需要从右上角到左下角的对角线,您需要矩阵位置[(0,n),(1,n-1),...,(n-1,1),( n,0)]。使用range(len(matrix))
可以轻松获得每对的第一个值。第二个值可以通过从方形矩阵的长度或宽度中减去第一个值(即行数)来获得(然后由于基于零的索引而减去一个)。现在,您只需查找每个行/列元组对即可获得索引。
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]
答案 1 :(得分:1)
我建议使用相应的numpy类,在本例中为numpy.matrix
。然后,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]]
如果输出必须是列表,则可以使用tolist()
轻松转换:
print(mydiagonal.tolist()[0])
[5, 9, 13, 17, 21]
答案 2 :(得分:0)
很简单的代码
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
矩阵= [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]
结果[5,9,13,17,21]
#and the asc diagonal
print'Result',matrix[::6]
结果[1,7,13,19,25]