我有一个矩阵m
我想计算零的数量。
m=((2,0,2,2),(4,4,5,4),(0,9,4,8),(2,2,0,0))
我当前的代码如下:
def zeroCount(M):
return [item for row in M for item in row].count(0)
# list of lists is flattened to form single list, and number of 0 are counted
有什么办法可以更快地做到这一点吗?目前,我花费 0.4 秒在 4 x 4 矩阵上执行该函数 20,000 次,其中矩阵包含零的可能性与不包含零的可能性相同。
一些可能的起点(但我无法使其比我的代码更快地工作)是以下其他问题:计算 numpy 数组中的非零元素 https://stackoverflow.com/questions/3797158/counting-non-zero-elements-within-each-row-and-within-each-column-of-a-2d-numpy, 查找非零元素的索引 https://stackoverflow.com/questions/23159791/find-the-indices-of-non-zero-elements-and-group-by-values, and 计算可迭代中的非零元素 https://stackoverflow.com/questions/3393431/how-to-counting-not-0-elements-in-an-iterable.