如何获取对角线上方的元素并将其存储在数组中

时间:2014-11-29 00:03:26

标签: python

我用:

创建了一个矩阵
Matrix = [[0 for x in range(5)] for z in range(5)]

我正在尝试提取诊断上方的元素并将其存储在数组中。

例如:

    [0, 0, 0, 1, 1]
    [1, 0, 0, 0, 0]
    [1, 1, 0, 0, 1]
    [0, 1, 1, 0, 0]
    [0, 1, 0, 1, 0]
U=[0,0,1,1,0,0,0,0,1,0]

A=[1,4,9]
  [0,1,2]
  [2,3,6]

U=[4,9,2]

2 个答案:

答案 0 :(得分:2)

您可以使用列表理解。

from random import randrange

Matrix = [[randrange(10) for x in range(5)] for z in range(5)]
>>>Matrix
[[6, 3, 7, 9, 3], [8, 6, 4, 0, 4], [0, 0, 1, 3, 2], [7, 7, 2, 3, 7], [3, 3, 5, 6, 3]]

[Matrix[i][j] for i in range(0,5) for j in range(i+1,5)]
[3, 7, 9, 3, 4, 0, 4, 3, 2, 7]

答案 1 :(得分:0)

所以这是一个解决方案,我改变你的矩阵以生成任何随机数,这样你就可以更好地看到哪些数字被考虑在内。 TRIU = Triangle Upper是以给定格式获取Matrix的函数,并采用位于对角线上方的Upper Triangle。

#import numpy as np
from random import randrange

Matrix = [[randrange(10) for x in range(5)] for z in range(5)]

def triu(matrix):
    length = len(matrix[0])
    U = list()
    diagLine = 0

    for row in Matrix:
        length -= 1
        colCounter = 0
        for col in row:
            if colCounter > diagLine:
                U.append(col)
            colCounter += 1
        diagLine += 1

    return U



#print np.matrix(Matrix)
print triu(Matrix)

<强>结果:

[[0 0 2 4 0]
 [6 4 8 9 0]
 [6 2 2 3 0]
 [2 9 6 5 5]
 [1 5 8 9 2]]
[0, 2, 4, 0, 8, 9, 0, 3, 0, 5]
[Finished in 0.2s]