python - 查找列表中最常见的元素

在 Python 列表中查找最常见元素的有效方法是什么?

我的列表项可能无法散列,因此无法使用字典。 此外,在绘制的情况下,应返回索引最低的项目。示例:

>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'

最佳答案

更简单的单行:

def most_common(lst):
    return max(set(lst), key=lst.count)

https://stackoverflow.com/questions/1518522/

相关文章:

python - 将迭代器转换为列表的最快方法

python - 如何检查平面列表中是否有重复项?

python - Python中的多级 'collection.defaultdict'

linux - 目录中所有文件内容的总大小

linux - 如何仅在脚本期间设置环境变量?

linux - 如何设置 curl 以永久使用代理?

shell - 如何在后台运行命令并且没有输出?

python - Python 中 dict.clear() 和分配 {} 的区别

linux - 为什么 find -exec mv {} ./target/+ 不起作用?

linux - 为Linux目录下新创建的文件和子目录设置默认权限?