我有一个列表:
hello = ['1', '1', '2', '1', '2', '2', '7']
我想显示列表中最常见的元素,所以我使用了:
m = max(set(hello), key=hello.count)
但是,我意识到列表中可能有两个元素以相同的频率出现,例如上面列表中的 1 和 2。 Max 仅输出最大频率元素的第一个实例。
什么样的命令可以检查一个列表,看看两个元素是否都具有最大实例数,如果是,则输出它们?我在这里不知所措。
最佳答案
使用与当前类似的方法,您将首先找到最大计数,然后查找具有该计数的每个项目:
>>> m = max(map(hello.count, hello))
>>> set(x for x in hello if hello.count(x) == m)
set(['1', '2'])
或者,您可以使用漂亮的 Counter
类,可用于高效地计数:
>>> hello = ['1', '1', '2', '1', '2', '2', '7']
>>> from collections import Counter
>>> c = Counter(hello)
>>> c
Counter({'1': 3, '2': 3, '7': 1})
>>> common = c.most_common()
>>> common
[('1', 3), ('2', 3), ('7', 1)]
然后您可以使用列表理解来获取所有具有最大计数的项目:
>>> set(x for x, count in common if count == common[0][1])
set(['1', '2'])
关于具有相同数量实例的 Python max,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9961077/