python - 计算矩阵元素和时的值错误

标签 python python-3.x numpy matrix

我正在尝试编写一个将矩阵中的所有元素相加的函数。特殊的情况是,如果矩阵中某个元素为0,则将这个0以下的元素也算为0。例如:

matrix = 

[[0, 1, 1, 2], 

[0, 5, 0, 0],

[2, 0, 3, 3]] 

应该返回 9,因为 1+1+2+5=9

这是我的代码,我收到此错误,ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()。有人可以帮忙吗?

import numpy as np
def matrixElementsSum(matrix):
    a=np.array([matrix])
    sumofcolumn=0
    sum=0
    for x in range(len(a)): # x in matrix row
        for y in range(len(a[0])): #y in matrix col
            if a[x][y]==0:
                a[x+1][y]==0 #set next row same column=0
            sumofcolumn+=a[x][y] #sumofcolumn is a column sum
    for x in sumofcolumn:
        sum+=x
    return sum

最佳答案

你可以旋转、展平,它们使用简单的理解:

import numpy as np

matrix = [[0, 1, 1, 2], [0, 5, 0, 0], [2, 0, 3, 3]]
matrix = np.rot90(matrix).flatten()
indices = set(np.where(matrix==0)[0]+1) # set of indices to the right of 0 fast lookup
final = sum(e for i,e in enumerate(matrix) if i not in indices)
print(final)

输出:

9

当您旋转并展平时,您会得到:

[2 0 3 1 0 3 1 5 0 0 0 2]

如果您注意到,矩阵中上方有 0 的所有值现在左侧都有 0,您可以使用列表理解忽略这些,然后求结果的总和。

我确信有一种方法可以在不旋转的情况下做到这一点,但我觉得这种方式更容易可视化。

关于python - 计算矩阵元素和时的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49684310/

相关文章:

python - 子类化实现单例思想元类的类

python - 文件名约定匹配的正则表达式

python - 有没有更好的方法来编写这些 if 语句

python - 如何检查单元格中的值是否在范围内。基于此将不同的 'scores' 分配给新列

python - NumPy 使用 reshape 函数 reshape 数组

python - 是否可以删除(不仅仅是取消链接)类(class)?

python - 程序在套接字交互期间挂起

python - 如何从python中的另一个类调用函数?

python - 在 Django 中运行迁移时出现 mysqlclient 错误

python - NUMPY 实现 AES 比纯 python 慢得多