Python - 如何在不使用numpy的情况下得到矩阵上三角的总和?

时间:2016-05-20 13:00:01

标签: python

此问题与this one类似,但我想知道如何在不使用numpy的情况下执行此操作。如何用纯Python获得矩阵上三角的夏天?所以,例如,我有

matrix = [[1,  2,  3],
          [4,  5,  6],
          [7,  8,  9]]

我怎么能回来:

upper = [2,3,6]
upperSum = 11
lower = [4,7,8]
lowerSum = 19

7 个答案:

答案 0 :(得分:3)

对于方形矩阵:实际上我认为即使对于非方形矩阵也能正常运行。

>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(( m[i][i+1:] for i in range(len(m)) ), [])
[2, 3, 6]
>>> sum(( m[i][:i] for i in range(len(m)) ), [])
[4, 7, 8]

(使用 sum-flatten hack)

>>> sum([[1, 2], [3, 4]], [])
[1, 2, 3, 4]

答案 1 :(得分:0)

有代码示例:

matrix = [[1,  2,  3],
          [4,  5,  6],
          [7,  8,  9]]
upper = []
lower = []
for j in xrange(0, len(matrix)):
    for i in xrange(0, len(matrix)):
        if j>i:
            lower.append(matrix[j][i])
        elif j<i:
            upper.append(matrix[j][i])
        else:
            pass
upperSum = sum(upper)
lowerSum = sum(lower)

答案 2 :(得分:0)

请记住,只有每个子数组具有相同的长度时,这才有效。

def GetSum(array):
    total = 0
    #Set the default value of "total" to 0.
    for i in range(len(array)):
    #for every item in the array:
        total += array[i]
        #Append the current selected value in the array to the total.
    return total
    #Return the total
try:
    length = len(matrix)
    #Get the length of the "matrix" array.
    rowlength = len(matrix[0])
    #Get the length of rows (the sub arrays within the main array).
    upper = [matrix[0][rowlength-2],matrix[0][rowlength-1],matrix[1][upperlength-1]]
    #Get the upper corner of the matrix array.
    uppersum = GetSum(upper)
    #Get the sum of all the items in "upper".
    lower = [matrix[length-2][0],matrix[length-1][0],matrix[length-1][1]]
    #Get the lower corner of the matrix array.
    lowersum = GetSum(lower)
    #Get the sum of all the items in "lower".
except:
    print("Incorrect matrix dimensions :/")
    #print an error message

答案 3 :(得分:0)

upper = []
[upper.extend(matrix[i][i+1:]) for i in range(len(matrix))]
lower = []
[lower.extend(matrix[i][0:i]) for i in range(len(matrix))]

然后总结: - )

答案 4 :(得分:0)

带有sum和生成器表达式的单行:

matrix = [[1,  2,  3],
          [4,  5,  6],
          [7,  8,  9]]

size = 2
sum(sum(matrix[i][-size+i:]) for i in xrange(size)) # 11
sum(sum(matrix[-i-1][:size-i]) for i in xrange(size)) # 19

答案 5 :(得分:0)

你的对角线是矩阵[x] [x]。所以你的上三角形是矩阵[x] [x + n]中的所有东西,其中x&lt; n&lt; (matrix [x] .length - x) 以相同的方式,你的下三角形在矩阵[x] [x-n]中,0 <&lt; n&lt; X

所以基本上,只有两个for循环可以做到这一点:

for(i=0; i<matrix.length; i++){
    for(j=i+1; j < (matrix[x].length - x); j++){
        //your code, here we iterate on the upper triangle
    }
}

我相信你现在会发现如何在下三角形上做同样的事情!

答案 6 :(得分:-1)

A=np.random.randint(2,9,(6,6))
upper = []
lower = []
for i in range(0,len(A)):
    upper.extend(A[i][i+1:])
    lower.extend(A[i][0:i])
Uppersum = sum(upper)
Lowersum = sum(lower)