3

我有一个二维矩阵,它可以是任何大小,但总是一个正方形。我想遍历矩阵并为每个对角线元素(x在示例中)我想分配值,1-sum_of_all_other_values_in_the_row例如

Mtx = [[ x ,.2 , 0 ,.2,.2]
       [ 0 , x ,.4 ,.2,.2]
       [.2 ,.2 , x , 0, 0]
       [ 0 , 0 ,.2 , x,.2]
       [ 0 , 0 , 0 , 0, x]]

for i in enumerate(Mtx):
    for j in enumerate(Mtx):
        if Mtx[i][j] == 'x'
            Mtx[i][j] = 1-sum of all other [j]'s in the row

我不知道如何获得每行中 j 的总和

4

3 回答 3

5
for i,row in enumerate(Mtx): #same thing as `for i in range(len(Mtx)):`
    Mtx[i][i]=0
    Mtx[i][i]=1-sum(Mtx[i])

    ##could also use (if it makes more sense to you):
    #row[i]=0
    #Mtx[i][i]=1-sum(row)
于 2012-07-11T18:43:49.887 回答
1

你可以这样做:

from copy import copy
for i, row in enumerate(Mtx):
    row_copy = copy(row)
    row_copy.pop(i)
    row[i] = 1 - sum(row_copy)
于 2012-07-11T18:43:08.227 回答
1
mtx = [[ 0 ,.2 , 0 ,.2,.2],
       [ 0 , 0 , .4 ,.2,.2,],
       [.2 ,.2 , 0 , 0, 0],
       [ 0 , 0 ,.2 , 0,.2],
       [ 0 , 0 , 0 , 0, 0]]
for i in range(len(mtx)):
    summ=sum(mtx[i])
    mtx[i][i]=round(1-summ,2) #use round to get 0.4 instead of .39999999999999999
print(mtx)    

输出:

[[0.4, 0.2, 0, 0.2, 0.2], [0, 0.2, 0.4, 0.2, 0.2], [0.2, 0.2, 0.6, 0, 0], [0, 0, 0.2, 0.6, 0.2], [0, 0, 0, 0, 1.0]]
于 2012-07-11T18:48:03.270 回答