collections.Counter类统计列表元素出现次数

时间:2023-03-09 09:11:43
collections.Counter类统计列表元素出现次数

# 使用collections.Counter类统计列表元素出现次数

 from collections import Counter

 names = ["Stanley", "Lily", "Bob", "Well", "Peter", "Bob", "Well", "Peter", "Well", "Peter", "Bob",
"Stanley", "Lily", "Bob", "Well", "Peter", "Bob", "Bob", "Well", "Peter", "Bob", "Well"] names_counts = Counter(names) # 实例化Counter对象,可接收任何hashable序列,Counter对象可以像字典一样访问元素并返回出现的次数
print(names_counts["Stanley"])
#
print(names_counts)
# Counter({'Bob': 7, 'Well': 6, 'Peter': 5, 'Stanley': 2, 'Lily': 2}) top_three = names_counts.most_common(3) # 取出出现次数最多的三个元素
print(top_three)
# [('Bob', 7), ('Well', 6), ('Peter', 5)] more_names = ["Stanley", "Lily", "Bob", "Well"]
names_counts.update(more_names) # 使用update方法新增需要统计的序列
top_three = names_counts.most_common(3) # 取出出现次数最多的三个元素
print(top_three)
# [('Bob', 8), ('Well', 7), ('Peter', 5)] names_counts = Counter(names)
more_names_counts = Counter(more_names)
print(names_counts)
# Counter({'Bob': 7, 'Well': 6, 'Peter': 5, 'Stanley': 2, 'Lily': 2})
print(more_names_counts)
# Counter({'Stanley': 1, 'Lily': 1, 'Bob': 1, 'Well': 1})
print(names_counts - more_names_counts) # 减去次数
# Counter({'Bob': 6, 'Well': 5, 'Peter': 5, 'Stanley': 1, 'Lily': 1})
print(names_counts + more_names_counts) # 合并次数
# Counter({'Bob': 8, 'Well': 7, 'Peter': 5, 'Stanley': 3, 'Lily': 3})

参考资料:
  Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).