Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python counter

作者:我在坚强也需要有人疼   发布日期:2026-01-23   浏览:44

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多进程

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

python中的yield

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站