简体   繁体   English

Python Dict超过一个Max值

[英]Python Dict more than one Max value

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. 我正在使用列表使用以下行从列表中的一组项中找到最大值: x=max(dictionary, key=dictionary.get)除非字典中的两个或多个相同,否则此方法行之有效似乎只是选择完全随机时的最大值之一。 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}将返回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)]

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, eg using itertools.takewhile : 不幸的是, most_common的参数n为您提供了n最大元素,而并非所有元素都具有最大值,因此您需要手动过滤它们,例如使用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)]

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

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