【问题标题】:Assigning a list element with the sum of the other elements用其他元素的总和分配一个列表元素
【发布时间】:2012-07-11 10:59:54
【问题描述】:

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

【问题讨论】:

    标签: python arrays for-loop matrix


    【解决方案1】:
    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)
    

    【讨论】:

    • @DSM -- 是的。有时我会专注于问题的“困难”部分,而忘记了小细节。谢谢。
    • 想想看,你也没有真正使用row;不过,显然你可以。现在我们正在骑自行车。 :^)
    • 完美,效果很好,感谢您的出色回答。 _ 是内置在“技巧”中的 python 吗?
    • @adohertyd _ 只是一个变量名。
    • @adohertyd -- 完全不需要嵌套循环:)。
    【解决方案2】:

    你可以这样做:

    from copy import copy
    for i, row in enumerate(Mtx):
        row_copy = copy(row)
        row_copy.pop(i)
        row[i] = 1 - sum(row_copy)
    

    【讨论】:

    • 对,我重新阅读了你的代码,我的评论是错误的。我会删除。
    • 感谢 badzil,但我认为其他答案更容易一些。
    • 你也可以通过row_copy=row[:]摆脱对copy的依赖。仅供参考。
    • @inspectorG4dget -- 本来我也认为你是对的,但他的解决方案还可以,因为他从复制的行中弹出,而不是他分配到的行。
    • @badzil:您的代码是正确的。对于错误报告,我深表歉意。立即删除。
    【解决方案3】:
    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]]
    

    【讨论】:

    • 问题中没有提到 x == 0。
    • @mgilson 我可以指定 0 开头而不是 x。谢谢 Ashwini,你总是为我的问题提供很好的答案。
    猜你喜欢
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多