寻找lis模式

2024-04-27 03:49:53 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

Python 3.4包含方法^{},因此很简单:

>>> from statistics import mode
>>> mode([1, 1, 2, 3, 3, 3, 3, 4])
 3

列表中可以有任何类型的元素,而不仅仅是数字元素:

>>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
 'red'

您可以使用^{}包中提供的^{},该包具有mode类函数

from collections import Counter
data = Counter(your_list_in_here)
data.most_common()   # Returns all unique items and their counts
data.most_common(1)  # Returns the highest occurring item

注意:计数器是Python2.7中的新功能,在早期版本中不可用。

您可以使用max函数和键。看看python max function using 'key' and lambda expression

max(set(list), key=list.count)

相关问题 更多 >