计算python字典中某个值出现的次数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48371856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
count the number of occurrences of a certain value in a dictionary in python?
提问by RowanX
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?
例如,如果我想将“0”的出现次数计算为一个值而不必迭代整个列表,这是否可能以及如何进行?
回答by Kasramvd
As I mentioned in comments you can use a generator within sum()
function like following:
正如我在评论中提到的,您可以在sum()
函数中使用生成器,如下所示:
sum(value == 0 for value in D.values())
Or as a slightly more optimized and functional approach you can use map
function as following:
或者作为稍微优化和功能性的方法,您可以使用map
如下函数:
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.
请注意,虽然map
在这种情况下使用function 可能会更优化,但为了获得关于这两种方法的全面和一般的想法,您还应该为相对较大的数据集运行基准测试。然后您可以决定何时使用哪个以获得更高的性能。
回答by blacksite
Alternatively, using collections.Counter
:
或者,使用collections.Counter
:
from collections import Counter
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
Counter(D.values())[0]
# 3
回答by user1767754
You can count it converting it to a list as follows:
您可以将其转换为列表,如下所示:
D = {'a': 97, 'c': 0 , 'b':0,'e': 94, 'r': 97 , 'g':0}
print(list(D.values()).count(0))
>>3
Or iterating over the values:
或者迭代这些值:
print(sum([1 for i in D.values() if i == 0]))
>>3