计算python字典中某个值出现的次数? [英] count the number of occurrences of a certain value in a dictionary in python?

查看:60
本文介绍了计算python字典中某个值出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的东西:

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

例如,如果我想将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?

推荐答案

正如我在评论中提到的,您可以在 sum() 函数中使用生成器:

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

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

或者作为稍微优化和功能性的方法,您可以通过将整数的 __eq__ 方法作为构造函数传递来使用 map 函数.

Or as a slightly more optimized and functional approach you can use map function by passing the __eq__ method of the integer as the constructor function.

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

基准:

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

请注意,虽然在这种情况下使用 map 函数可能会更优化,但是为了对这两种方法有更全面和一般的了解,您还应该针对相对较大的数据集运行基准测试.然后,您可以根据您拥有的结构和数据量使用最合适的方法.

Note that although using map function in this case may be more optimized, but in order to have a more comprehensive and general idea about the two approaches you should run the benchmark for relatively large datasets as well. Then, you can use the most proper approach based on the structure and amount of data you have.

这篇关于计算python字典中某个值出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆