python – 使用其他元素的总和分配list元素

我有一个2d矩阵,可以是任何大小,但总是一个正方形.我想循环遍历矩阵,并且对于每个对角元素(示例中为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的总和

最佳答案

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)
点赞