我正在使用 statistics.mode([1, 1, 2, 2, 3]) 来查找模式,但我得到:
no unique mode; found 2 equally common values
当找到多个模式时,如何输出 1 或 2?
请您参考如下方法:
请注意,在 Python 3.8 中 statistics.mode 的行为已更改:
Changed in version 3.8: Now handles multimodal datasets by returning the first mode encountered. Formerly, it raised StatisticsError when more than one mode was found.
在你的例子中:
from statistics import mode
mode([1, 1, 2, 2, 3])
# 1
同样从 Python 3.8 开始,您也可以使用 statistics.multimode按照首次遇到的顺序返回最常出现的值的列表:
from statistics import multimode
multimode([1, 1, 2, 2, 3])
# [1, 2]
