统计出序列(列表、元组、字符串等等)中元素的频度

在处理数据时,有时需求为统计出序列(列表、元组、字符串等等)中元素的频度,下面以简单的小实例讲解个人求解方式,细节讲解都在代码注释中。

1.方式一,普通的遍历统计

from random import randint

# 随机生成20个10以内的数字
random_list = [randint(1, 10) for _ in range(20)]
print(random_list)
word_count = {}
# 遍历列表统计元素频度,保存进字典中
# 第一次出现就添加到字典中,频度为0
# 重复出现时,就在原频度基础上加1
for i in random_list:
    if i not in word_count:
        word_count[i] = 0
    else:
        word_count[i] = word_count[i] + 1
# 排序,统计出频度最高的前3个元素及频度
# lambda x: x[1]  意思是以items()返回的元组的第二个元素排序即频度排序
print(sorted(word_count.items(), key=lambda x: x[1], reverse=True)[0:3])

2.方式二,Counter类

from random import randint
from collections import Counter

# 随机生成20个10以内的数字
random_list = [randint(1, 10) for _ in range(20)]
print(random_list)
# 使用collections下的Counter类,
# 统计传入的序列中的元素出现次数,自动降序排列,除了most_common(n)列出出现次数最多的n个数、elements()有序列出元素外,
# 其他方法和字典拥有的方法一样的。
count = Counter(random_list)
print(count.most_common(3))

你可能感兴趣的:(统计出序列(列表、元组、字符串等等)中元素的频度)