Counter()函数:对序列中的元素进行计数,返回一个字典
发布时间:2023-06-16 21:40:05
Counter()函数是Python标准库collections中的一个有用函数,用于对序列中的元素进行计数,并返回一个字典。
Counter()函数可以接受任何可迭代对象,如列表、元组、字符串等,如下所示:
>>> from collections import Counter
>>> lst = ['a', 'b', 'c', 'a', 'b', 'a']
>>> Counter(lst)
Counter({'a': 3, 'b': 2, 'c': 1})
在上述例子中,Counter()函数接受了一个列表lst,返回一个字典,其中字典的键是列表元素,值是元素在列表中出现的次数。
对于字符串也可以使用Counter()函数,例如:
>>> s = 'aabbccd'
>>> Counter(s)
Counter({'a': 2, 'b': 2, 'c': 2, 'd': 1})
对于Counter()函数返回的字典,可以使用字典的常规方法进行访问和操作,如下所示:
>>> c = Counter(lst)
>>> c['a']
3
>>> c['b']
2
>>> c['d']
0
>>> c.update(['a', 'd'])
>>> c
Counter({'a': 4, 'b': 2, 'c': 1, 'd': 1})
>>> c.most_common(2)
[('a', 4), ('b', 2)]
在上述例子中,先创建了一个Counter对象c,然后可以通过访问字典的方式获取计数结果。可以使用update()方法更新计数结果,也可以使用most_common()方法获取出现次数最多的元素。
Counter()函数对于统计频率分布非常有用,例如统计文本中单词出现的频率,示例代码如下所示:
import re
from collections import Counter
text = 'This is a sample text with several words that will be counted repeatedly. It is a good example for testing purposes.'
words = re.findall('\w+', text.lower())
freq_dist = Counter(words)
for word, freq in freq_dist.most_common(10):
print(word, freq)
在上述例子中,首先使用正则表达式获取到text中的所有单词,然后使用Counter()函数统计每个单词出现的频率。最后使用most_common()方法获取出现频率最高的10个单词,并打印输出。
总之,在Python中使用Counter()函数很容易实现元素计数,可以帮助我们快速统计元素出现的频率,是一种非常有用的技巧。
