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

时间:2012-07-11 18:38:49

标签: python arrays for-loop matrix

我有一个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的总和

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

答案 2 :(得分: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]]