在 Python 中查找列表中最常见的元素
Python 中要查找列表中最常见的元素:
- 使用 collections.Counter() 类创建一个计数器对象。
- 使用 most_common() 方法获取列表中最常见的元素。
from collections import Counter
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
counter = Counter(a_list)
most_common = counter.most_common(1)[0][0]
print(most_common) # ?️ one
most_common_2 = counter.most_common(2)
print(most_common_2) # ?️ [('one', 3), ('two', 2)]
我们使用 collections.Counter 类来计算每个列表项的出现次数。
collections 模块中的 Counter 类是 dict 类的子类。
该类基本上是键数对的映射。
from collections import Counter
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
counter = Counter(a_list)
print(counter) # ?️ Counter({'one': 3, 'two': 2, 'three': 1})
Counter 对象实现了 most_common() 方法,该方法返回 N 个最常见元素的列表及其从最常见到最少的计数。
from collections import Counter
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
counter = Counter(a_list)
most_common = counter.most_common(1)[0][0]
print(most_common) # ?️ one
# ?️ [('one', 3)]
print(counter.most_common(1))
Python 索引是从零开始的,因此列表中的第一项的索引为 0,最后一项的索引为 -1 或 len(my_list) – 1。
如果没有向 most_common 方法提供参数,它将列出所有元素计数。
我们还可以使用此方法获取列表中最常见的 N 个元素。
from collections import Counter
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
counter = Counter(a_list)
n = 2
most_common_n = counter.most_common(n)
print(most_common_n) # ?️ [('one', 3), ('two', 2)]
我们将 2 作为参数传递给 most_common() 方法,因此它返回列表中最常见的 2 个元素。
或者,我们可以使用 max() 函数。
使用 max() 查找列表中最常见的元素
要查找列表中最常见的元素:
- 使用 max() 函数。
- 将 key 参数传递给函数。
- 使用 list.count() 方法计算每个元素的出现次数。
- max() 函数将返回最常见的元素。
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
most_common = max(set(a_list), key=a_list.count)
print(most_common) # ?️ one
我们使用 max() 函数来获取列表中最常见的元素。
max() 函数返回可迭代对象中的最大项或两个或多个参数中最大的一个。
my_list = [15, 45, 30]
result = max(my_list)
print(result) # ?️ 45
max 函数也有一个可选的键参数。
我们使用 set() 类将列表转换为集合对象以删除任何重复项。
你可以想象:
- 集合中的每个元素都会调用 list.count() 方法。
- 该方法返回元素在列表中出现的次数。
- max() 函数返回最常见的列表元素。
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
most_common = max(set(a_list), key=a_list.count)
print(most_common) # ?️ one
list.count() 方法接受一个值并返回所提供的值在列表中出现的次数。
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
print(a_list.count('one')) # ?️ 3
print(a_list.count('two')) # ?️ 2
print(a_list.count('abc')) # ?️ 0
或者,我们可以使用 statistics.mode() 方法。
使用 statistics.mode() 查找列表中最常见的元素
使用 statistics.mode() 方法查找列表中最常见的元素,例如 most_common = mode(a_list)。 mode() 方法返回提供的可迭代对象中最常见的单个值。
from statistics import mode
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
most_common = mode(a_list)
print(most_common) # ?️ one
statistics.mode() 方法接受一个可迭代对象并返回可迭代对象中最常见的值。
from statistics import mode
a_list = ['one', 'one', 'one', 'two', 'two', 'three']
print(mode([1, 1, 1, 2, 2, 3])) # ?️ 1
# ?️ one
print(mode(['one', 'one', 'one', 'two', 'two', 'three']))
如果有多个值具有相同的频率,则该方法返回第一个遇到的值。
如果提供的可迭代对象为空,则该方法会引发 StatisticsError 异常。
在 Python v3.8 之前,如果可迭代对象中没有最常见的元素,则 statistics.mode() 方法会引发 StatisticsError 异常,例如 如果前两个出现的次数相同。