# 在 Python 中查找列表的模式

Samyak Jain 2023年1月30日

## 在 Python 中使用 `max()` 函数和一个键来查找列表的模式

`max()` 函数可以返回给定数据集的最大值。带有 `count()` 方法的 `key` 参数比较并返回每个元素在数据集中出现的次数。

``````A = [10, 30, 50, 10, 50, 80, 50]
print("Mode of List A is % s" % (max(set(A), key=A.count)))
B = ["Hi", 10, 50, "Hi", 100, 10, "Hi"]
print("Mode of List B is % s" % (max(set(B), key=B.count)))
``````

``````Mode of List A is 50
Mode of List B is Hi
``````

``````C = [10, 30, "Hello", 30, 10, "Hello", 30, 10]
print("Mode of List C is % s" % (max(set(C), key=C.count)))
``````

``````Mode of List C is 10
``````

## 在 Python 中使用集合包中的 `Counter` 类查找列表的模式

collections 包中的 `Counter` 类用于计算给定数据集中每个元素出现的次数。

`Counter` 类的 `.most_common()` 方法返回一个列表，该列表包含具有每个唯一元素及其频率的两项元组。

``````from collections import Counter

A = [10, 10, 30, 10, 50, 30, 60]
Elements_with_frequency = Counter(A)
print(Elements_with_frequency.most_common())
``````

``````[(10, 3), (30, 2), (50, 1), (60, 1)]
``````

`Counter(list_name).most_common(1)[0][0]` 函数将返回列表所需的模式。当列表中存在多个模式时，它将返回最小的模式。

``````from collections import Counter

A = [10, 10, 30, 10, 50, 30, 60]
print("Mode of List A is % s" % (Counter(A).most_common(1)[0][0]))
``````

``````Mode of List A is 10
``````

## 在 Python 中使用 `statistics` 模块中的 `mode()` 函数查找列表的模式

python 统计模块中的 `mode()` 函数将一些数据集作为参数并返回其模式值。

``````from statistics import mode

A = [10, 20, 20, 30, 30, 30]
print("Mode of List A is % s" % (mode(A)))
B = ["Yes", "Yes", "Yes", "No", "No"]
print("Mode of List B is % s" % (mode(B)))
``````

``````Mode of List A is 30
Mode of List B is Yes
``````

## 在 Python 中使用统计模块中的 `multimode()` 函数查找模式列表

``````from statistics import multimode

A = [10, 20, 20, 30, 30, 30, 20]
print("Mode of List A is % s" % (multimode(A)))
B = ["Yes", "Yes", "Yes", "No", "No", "No", "Maybe", "Maybe"]
print("Mode of List B is % s" % (multimode(B)))
``````

``````Mode of List A is [20, 30]
Mode of List B is ['Yes', 'No']
``````