繁体   English   中英

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']

>>> dictionary = { 'A': 2, 'B': 1, 'C': 2 }
>>> maxValue = max(dictionary.values())
>>> [k for k, v in dictionary.items() if v == maxValue]
['C', 'A']

您还可以使用计数器来获取按“最常见”(最高值)排序的项目:

>>> from collections import Counter
>>> c = Counter(dictionary)
>>> c.most_common()
[('C', 2), ('A', 2), ('B', 1)]

不幸的是, 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