且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

计算在python中的字典中某个值出现的次数?

更新时间:2022-12-10 09:54:49

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

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

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

或者作为一种稍微优化和实用的方法,您可以按以下方式使用map函数:

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

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 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.