如何获得具有相同最大值的所有键? [英] How to get all the keys with the same highest value?
本文介绍了如何获得具有相同最大值的所有键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个字典及其相应的频率值:
If I have a dictionary with their corresponding frequency values:
numbers = {a: 1, b: 4, c: 1, d: 3, e: 3}
要找到最高的东西,我知道的是:
To find the highest, what I know is:
mode = max(numbers, key=numbers.get)
print mode
并显示:
b
但如果我有:
numbers = {a: 1, b: 0, c: 1, d: 3, e: 3}
并应用上面的"max"函数,输出为:
and apply the 'max' function above, the output is:
d
我需要的是:
d,e
或类似的东西,同时显示两个键.
Or something similar, displaying both keys.
推荐答案
numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}
max_value = max(numbers.values())
[k for k,v in numbers.iteritems() if v == max_value]
打印
['e', 'd']
它的作用是,通过.iteritems
遍历所有条目,然后检查该值是否为最大值,如果是,则将该键添加到列表中.
what it does is, loop over all entries via .iteritems
and then check if the value is the maximum and if so add the key to a list.
这篇关于如何获得具有相同最大值的所有键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文