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"])
# 2
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})

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值