在字典中找到最少出现次数的值

2024-10-01 13:28:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个问题,这个问题要求我返回字典中出现频率最低的值,除了使用几个不同的计数之外,我似乎无法解决这个问题,但是在检查中,字典中没有一个固定数量的值。在

For example, suppose the dictionary contains mappings from students' names (strings) to their ages (integers). Your method would return the least frequently occurring age. Consider a dictionary variable d containing the following key/value pairs:

{'Alyssa':22, 'Char':25, 'Dan':25, 'Jeff':20, 'Kasey':20, 'Kim':20, 'Mogran':25, 'Ryan':25, 'Stef':22}

Three people are age 20 (Jeff, Kasey, and Kim), two people are age 22 (Alyssa and Stef), and four people are age 25 (Char, Dan, Mogran, and Ryan). So rarest(d) returns 22 because only two people are that age.

有人能帮我指一下正确的方向吗?谢谢!在


Tags: andtheagedictionary字典peoplearedan
3条回答

您可以为计数器创建一个空dict,然后循环查看您得到的dict,并在第二个dict中为相应的值加1,然后返回第二个dict中具有最小值的元素的键

from collections import Counter
min(Counter(my_dict_of_ages.values()).items(),key=lambda x:x[1])

我想会的

对集合的成员进行计数是collections.Counter的工作:

d={'Alyssa':22, 'Char':25, 'Dan':25, 'Jeff':20, 'Kasey':20, 'Kim':20, 'Mogran':25, 'Ryan':25, 'Stef':22}
import collections
print collections.Counter(d.values()).most_common()[-1][0]
22

相关问题 更多 >