Python:获取列表中出现频率最低的值

Python: Get the lowest, most frequent value of a list

大家好! 你能帮我解决以下问题吗?我没有设法为我的问题找到有效的解决方案。非常感谢任何帮助!提前感谢大家!

我的问题:作为第一步,我想确定给定整数列表中出现频率最高的值.作为第二步,如果有多个最频繁的值,我想取其中最低的。

示例:给定以下列表,我想接收“5”,因为它是最低、最频繁的值.

list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]

你能帮帮我吗?谢谢!

In [24]: list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
    ...:

In [25]: max(sorted(set(list)), key=list.count)
Out[25]: 5

使用内置的 Counter class:

可以在线性时间内从多个候选中获得最常见的值
from collections import Counter

l = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
counter = Counter(l)
_, top_freq = counter.most_common(1)[0]
lower_most_common = min(key for key, freq in counter.items() if freq == top_freq)