ado*_*tyd 3 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
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何获得每一行中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)
Run Code Online (Sandbox Code Playgroud)