from collections import Counter
# 创建一个 Counter 对象
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(data)
# 输出 Counter 对象
print(counter) # 输出: Counter({'apple': 3, 'banana': 2, 'orange': 1})
# 访问特定元素的计数
print(counter['apple']) # 输出: 3
# 获取最常见的元素
most_common = counter.most_common(2)
print(most_common) # 输出: [('apple', 3), ('banana', 2)]
# 更新计数
more_data = ['apple', 'grape', 'grape']
counter.update(more_data)
print(counter) # 输出: Counter({'apple': 4, 'grape': 2, 'banana': 2, 'orange': 1})
# 减少计数
counter.subtract({'apple': 1})
print(counter) # 输出: Counter({'apple': 3, 'grape': 2, 'banana': 2, 'orange': 1})
Counter 是 Python 标准库 collections 模块中的一个类,用于计数可哈希对象。Counter(data) 创建一个 Counter 对象,其中 data 是一个可迭代对象(如列表、元组等)。counter['element'] 可以访问特定元素的计数。counter.most_common(n) 返回出现频率最高的 n 个元素及其计数。counter.update(iterable) 用于更新计数,可以传入另一个可迭代对象。counter.subtract(iterable) 用于减少计数,可以传入字典或可迭代对象。上一篇:python列表排序
下一篇:python多进程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站