发布于 4年前

Python 统计列表中元素的出现频率

这样做有多种方法,但是我最喜欢的是使用Python Counter类。

Python counter会跟踪容器中每个元素的频率。 Counter()返回一个字典,其中元素作为键,而频率作为值。

我们还使用most_common()函数来获取列表中的出现频率最高的元素。

# finding frequency of each element in a list
from collections import Counter
my_list = ['a','a','b','b','b','c','d','d','d','d','d']
count = Counter(my_list) # defining a counter object
print(count) # Of all elements
# Counter({'d': 5, 'b': 3, 'a': 2, 'c': 1})
print(count['b']) # of individual element
# 3
print(count.most_common(1)) # most frequent element
# [('d', 5)]
©2020 edoou.com   京ICP备16001874号-3