如何获取具有相同最高值的所有密钥?

2024-04-30 02:43:30 发布

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

如果我有一个对应频率值的字典:

numbers = {a: 1, b: 4, c: 1, d: 3, e: 3}

为了找到最高点,我所知道的是:

mode = max(numbers, key=numbers.get)
print mode

上面印着:

b

但如果我有:

numbers = {a: 1, b: 0, c: 1, d: 3, e: 3}

并应用上面的“max”函数,输出为:

d

我需要的是:

d,e

或者类似的东西,显示两个键。


Tags: key函数get字典modemax频率print
3条回答
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循环所有条目,然后检查该值是否为最大值,如果是,则将键添加到列表中。

collections.Counter对象对此也很有用。它为您提供了一个.most_common()方法,该方法将为您提供所有可用值的键和计数:

from collections import Counter
numbers = Counter({'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3})
values = list(numbers.values())
max_value = max(values)
count = values.count(max_value)
numbers.most_common(n=count)
numbers = {'a': 1, 'b': 4, 'c': 1, 'd':4 , 'e': 3}
mx_tuple = max(numbers.items(),key = lambda x:x[1]) #max function will return a (key,value) tuple of the maximum value from the dictionary
max_list =[i[0] for i in numbers.items() if i[1]==mx_tuple[1]] #my_tuple[1] indicates maximum dictionary items value

print(max_list)

此代码将在O(n)中工作。在求最大值时为O(n),在列表理解中为O(n)。所以总的来说还是O(n)。

注:O(2n)等于O(n)。

相关问题 更多 >