Python Dict超过一个Max值 [英] Python Dict more than one Max value
问题描述
我正在使用列表使用以下行从列表中的一组项目中找到最大值: x = max(dictionary,key = dictionary.get)
除非字典中的两个或多个值相同,否则此方法工作正常,似乎只是在完全随机的情况下选择了最大值之一.有没有一种方法可以打印两个最大值,可能在列表中,例如: dictionary = {'A':2,'B':1,'C':2}
,它将返回 x = ['A','C']
I am using a list to find a max value from a group of items in the list using the line: x=max(dictionary, key=dictionary.get)
This works fine unless two or more values in the dictionary are the same, it just seems to choose one of the max at complete random.
Is there a way that I can get it to print both of the max values, possibly in a list eg:dictionary={'A':2,'B':1,'C':2}
which will return x=['A','C']
推荐答案
>>> dictionary = { 'A': 2, 'B': 1, 'C': 2 }
>>> maxValue = max(dictionary.values())
>>> [k for k, v in dictionary.items() if v == maxValue]
['C', 'A']
您还可以使用计数器来获取按最常见"(最高值)排序的项目:
You can also use a counter to get the items sorted by "most common" (highest value):
>>> from collections import Counter
>>> c = Counter(dictionary)
>>> c.most_common()
[('C', 2), ('A', 2), ('B', 1)]
不幸的是,参数 n
到 most_common
可以为您提供 n
个最大元素,而并非所有元素都具有最大值,因此您需要过滤手动,例如使用 itertools.takewhile
:
Unfortunately, the parameter n
to most_common
gives you n
maximum elements, and not all with the maximum value, so you need to filter them manually, e.g. using itertools.takewhile
:
>>> from itertools import takewhile
>>> maxValue = c.most_common(1)[0][1]
>>> list(takewhile(lambda x: x[1] == maxValue, c.most_common()))
[('C', 2), ('A', 2)]
这篇关于Python Dict超过一个Max值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!