简体   繁体   English

如何计算一个值在字典中出现的次数?

[英]How to count the number of times a value appears in a dictionary?

I've been tasked with creating a "pown-chess" game, and i'm trying to figure out how to code the win condition.我的任务是创建一个“pown-chess”游戏,我正试图弄清楚如何编写获胜条件。 Is there any way to have python count the number of times a given value appears in a dictionary?有没有办法让 python 计算给定值在字典中出现的次数?

You can make a list of the dict's values, and use its count method.您可以列出 dict 的值,并使用它的count方法。

result = list(mydict.values()).count(value)

The simplest way for a beginner (like me) is to apply Counter from collections to the values of your dictionary:初学者(像我一样)最简单的方法是将 collections 中的 Counter 应用于字典的值:

from collections import Counter
d=dict([(2,1),(3,1),(4,2),(5,1),(6,3),(7,2),(8,3)])
# d:(key,val) --> dd:(val,freq_of_val_in_d) 
dd=Counter(d.values())
print(dd)

gives:给出:

Counter({1: 3, 2: 2, 3: 2})

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

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