python - 使用其他元素的总和分配列表元素

标签 python arrays for-loop matrix

我有一个二维矩阵,它可以是任意大小但始终是正方形。我想遍历矩阵并为每个对角线元素(示例中的 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)

关于python - 使用其他元素的总和分配列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11439213/

相关文章:

python - Tensorflow 2.0 不计算梯度

arrays - 删除 postgreSQL 中的数组值

python - 计算数组中的像素

python - 根据列值创建列表,并使用该列表从 df 中的字符串列中提取单词,而不用 for 循环覆盖行值

Python - 我可以使用 for 循环打印出具有连续数字的变量吗?

python - 如何使用 jsonpath + Python 获取某些元素?

Python:Chi 2 测试产生错误结果 (chi2_contingency)

python - 没有这样的列 : chat_conversation. 创建日期

android - Arrayadapter.getcount 空点异常

c - 在 C 运行时生成嵌套循环