简体   繁体   English

Python:计算多值字典中的值

[英]Python: Count Values in multi-value Dictionary

How can I count the number of a specific values in a multi-value dictionary?如何计算多值字典中特定值的数量?

For example, if I have the keys A and B with different sets of numbers as values, I want get the count of each number amongst all of the dictionary's keys.例如,如果我的键AB具有不同的数字集作为值,我想获取字典所有键中每个数字的计数。

I've tried this code, but I get 0 instead of 2.我试过这段代码,但我得到的是 0 而不是 2。

dic = {'A':{0,1,2},'B':{1,2}}
print(sum(value == 1 for value in dic.values()))

Counter is a good option for this, especially if you want more than a single result: Counter是一个不错的选择,特别是如果您想要多个结果:

from collections import Counter

from itertools import chain
from collections import Counter
count = Counter(chain(*(dic.values())))

In the REPL:在 REPL 中:

>>> count
Counter({1: 2, 2: 2, 0: 1})
>>> count.get(1)
2

Counter simply tallies each item in a list. Counter只是简单地计算列表中的每个项目。 By using chain we treat a list of lists as simply one large list, gluing everything together.通过使用chain ,我们将列表列表视为一个大列表,将所有内容粘合在一起。 Feeding this right to Counter does the work of counting how many of each item there is.将此权限提供给Counter可以计算每个项目的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM