python 计算一个数在列表中出现次数_计算在python中的字典中某个值出现的次数?...

该博客探讨了如何在Python字典中高效地计算值为0的项数量,提供了两种方法:一种是使用生成器表达式与`sum()`函数结合,另一种是利用`map()`函数配合等式比较。通过基准测试,虽然`map()`方法在小数据集上可能更优,但为了全面评估,建议在大型数据集上进行测试以确定最佳实践。
摘要由CSDN通过智能技术生成

1586010002-jmsa.png

If I have got something like this:

D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}

If I want for example to count the number of occurrences for the "0" as a value without having to iterate the whole list, is that even possible and how?

解决方案

As I mentioned in comments you can use a generator within sum() function like following:

sum(value == 0 for value in D.values())

Or as a slightly more optimized and functional approach you can use map function as following:

sum(map((0).__eq__, D.values()))

Benchmark:

In [56]: %timeit sum(map((0).__eq__, D.values()))

1000000 loops, best of 3: 756 ns per loop

In [57]: %timeit sum(value == 0 for value in D.values())

1000000 loops, best of 3: 977 ns per loop

Note that although using map function in this case may be more optimized but in order to achieve a comprehensive and general idea about the two approaches you should run the benchmark for relatively large datasets as well. Then you can decide when to use which in order to gain the more performance.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值