python - 如何从数组中获取最具代表性的对象

标签 python algorithm arrays performance list

我有一个包含一些对象的数组,并且有几个对象是相似的。例如:fruit = [apple, orange, apple, banana, banana, orange, apple, apple]

从这个数组中获取最多代表对象的最有效方法是什么?在这种情况下,它将是“苹果”,但您将如何以有效的方式进行计算?

最佳答案

不要重新发明轮子。在 Python 2.7+ 中你可以使用 the Counter class :

import collections
fruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple']
c=collections.Counter(fruit)
print(c.most_common(1))
# [('apple', 4)]

如果您使用的是旧版本的 Python,那么您可以下载 Counter here .

虽然自己知道如何实现这样的东西很好,但习惯使用 Counter 也是一个好主意,因为它是(或将成为)标准库的一部分。

关于python - 如何从数组中获取最具代表性的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2184336/

相关文章:

python - 使用 Python 将 Excel 转换为 JSON

python - 用于选择二维数组元素的矢量化代码

algorithm - 蛇形图像遍历算法的名称是什么?

algorithm - 公牛和奶牛 - 破解密码 - 算法

php - 将数组存储到数据库php

c - 使用strtod后如何将double值转换为char数组?在C中

python - 如何使用 NLTK snowball 词干提取器来提取西类牙语单词列表 Python

Python WAV "TypeError: data type not understood"错误

c# - 打印总和为特定值的所有子集

arrays - 如何将矩阵转换为数组数组?