加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 计算与元组元组中的模式匹配的元素

发布时间:2020-12-20 12:24:27 所属栏目:Python 来源:网络整理
导读:我有一个矩阵m,我想计算零的数量. m=((2,2,2),(4,4,5,4),(0,9,8),(2,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 有没
我有一个矩阵m,我想计算零的数量.

m=((2,2,2),(4,4,5,4),(0,9,8),(2,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乘4矩阵上执行20,000次函数,其中矩阵同样可能包含零,因为它们不是.

一些可能的起点(但我无法比我的代码更快地工作)是其他问题:counting non-zero elements in numpy array,finding the indices of non-zero elements和counting non-zero elements in iterable.

解决方法

到目前为止最快的:

def count_zeros(matrix):
    total = 0
    for row in matrix:
        total += row.count(0)
    return total

对于2D元组,你可以use a generator expression:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读