计算与元组中的模式匹配的元素 [英] Counting elements matching a pattern in a tuple of tuples
问题描述
我有一个矩阵m
,我要在其中计算零的数量.
I have a matrix m
where I would like to calculate the number of zeros.
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次功能,其中矩阵很可能包含零,而不是不包含零.
Is there any way to do this quicker? Currently, I'm taking 0.4s to execute the function 20,000 times on 4 by 4 matrices, where the matrices are equally likely to contain zeros as they are not.
其他一些问题可能是一些开始的地方(但是我无法使其工作比我的代码快):找到非零元素的索引,然后对可迭代的非零元素进行计数.
Some possible places to start (but which I could not make to work faster than my code) are these other questions: counting non-zero elements in numpy array, finding the indices of non-zero elements, and counting non-zero elements in iterable.
推荐答案
到目前为止最快的方法:
The fastest so far:
def count_zeros(matrix):
total = 0
for row in matrix:
total += row.count(0)
return total
对于2D元组,您可以使用生成器表达式:
def count_zeros_gen(matrix):
return sum(row.count(0) for row in matrix)
时间比较:
%timeit [item for row in m for item in row].count(0) # OP
1000000 loops, best of 3: 1.15 µs per loop
%timeit len([item for row in m for item in row if item == 0]) # @thefourtheye
1000000 loops, best of 3: 913 ns per loop
%timeit sum(row.count(0) for row in m)
1000000 loops, best of 3: 1 µs per loop
%timeit count_zeros(m)
1000000 loops, best of 3: 775 ns per loop
对于基线:
def f(m): pass
%timeit f(m)
10000000 loops, best of 3: 110 ns per loop
这篇关于计算与元组中的模式匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!