collection counter 类 找出序列中出现次数最多的元素

本文介绍如何利用Python中的Counter类快速统计列表内各元素出现的频次,并通过实例展示了如何找出出现次数最多的元素。此外,还介绍了Counter对象支持的基本数学运算,包括两个Counter之间的加法和减法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


'''
找出序列中的出现次数最多的元素
运用
colections 中的counter类中的most_common()方法

底层:counter是一个字典 ,在元素和次数之间作了映射
'''
lists = ['look', 'see', 'aaa', 'aaa', 'b', 'c',
'aaa', 'aaa', 'c', 'b', 'b', 'aaa', 'aaa']
lists2 = ['look', 'see', 'aaa', 'b', 'c',
'aaa', 'aaa', 'c', 'b', 'b', 'aaa', 'aaa']

from collections import Counter

word_counts = Counter(lists)
top_three = word_counts.most_common(3)
print(top_three)
print(word_counts['aaa'])

'''
[('aaa', 6), ('b', 3), ('c', 2)]
6
'''
word2_counts = Counter(lists2)
print(word2_counts)
'''
>>> Counter({'aaa': 5, 'b': 3, 'c': 2, 'look': 1, 'see': 1})
主要是我们的counter对象是可以进行各种数学运算操作结合起来使用

'''

a = word_counts + word2_counts
b = word_counts - word2_counts
print(a)
print(b)

'''
>>>Counter({'aaa': 11, 'b': 6, 'c': 4, 'look': 2, 'see': 2})
>>>Counter({'aaa': 1})
'''

'''
我们拿到源码
def most_common(self, n=None):
List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.

>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]

# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))

源码暂时贴在这里 我还不能理解

'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值