Python标准库之 collections.Counter

本文深入解析了Python标准库collections模块下的Counter类,介绍了其作为字典子类的特点,包括元素计数、初始化方式、常见操作如元素访问、元素删除及高级用法。Counter类适用于计数可哈希对象,类似于其他语言中的袋或多重集。

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

今天在看《数据科学入门》这本书的时候,看到一个Counter这个函数,从Python标准库文档( https://docs.python.org/3/library )中查了一下发现是标准库collections模块下的一个类。collections是Python标准库中的一种数据类型,它不是build-in类型之一,是标准库中的类型。

Built-in 类型

  • Truth Value Testing
  • Boolean Operations — and, or, not
  • Comparisons
  • Numeric Types — int, float, complex
  • Iterator Types
  • Sequence Types — list, tuple, range
  • Text Sequence Type — str
  • Binary Sequence Types — bytes, bytearray, memoryview
  • Set Types — set, frozenset
  • Mapping Types — dict
  • Context Manager Types
  • Other Built-in Types
  • Special Attributes

标准库数据类型

  • datetime — Basic date and time types
  • calendar — General calendar-related functions
  • collections — Container datatypes
  • collections.abc — Abstract Base Classes for Containers
  • heapq — Heap queue algorithm
  • bisect — Array bisection algorithm
  • array — Efficient arrays of numeric values
  • weakref — Weak references
  • types — Dynamic type creation and names for built-in types
  • copy — Shallow and deep copy operations
  • pprint — Data pretty printer
  • reprlib — Alternate repr() implementation
  • enum — Support for enumerations

以下是Python标准库文档中对Counter类的描述

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

主要含义就是 Counter 是字典的子类,元素被存储为字典的关键字,而它出现的次数被存储为值。

初始化

从一个可迭代的(iterable)对象(list、tuple、dict、字符串等)创建:

>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

Counter()创建的类型有一个字典类型的接口(可以直接通过方括号直接访问)。与字典不同的是,若访问的元素不存在会返回0,而不是一个KeyError。

>>> c = Counter(['eggs', 'ham'])
>>> c['bacon']                              # count of a missing element is zero
0

仅仅设置值为0不会将该元素删除。如果想要删除一个元素,则通过del来删除。

>>> c['sausage'] = 0                        # counter entry with a zero count
>>> del c['sausage']                        # del actually removes the entry

用法

counter_instance[‘element_key’] :返回element_key出现的频次
elements() : 返回所有的元素(重复的元素会重复出现)
most_common([n]) : 返回出现频率最高的n个元素。相同频次的元素顺序随机。

更多高级用法参考https://docs.python.org/3/library/collections.html#collections.Counter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值