python collections 常用库及其方法

Python 的 collections 模块提供了一系列高性能、专用的容器数据类型,用于替代 Python 内置的通用容器(如 listdicttuple 等)。以下是 collections 中常用的类和工具:


1. Counter

用途:统计可哈希对象的元素频率(如列表、字符串中的字符计数)。
示例

from collections import Counter
count = Counter("hello")  # Counter({'h': 1, 'e': 1, 'l': 2, 'o': 1})

2. defaultdict

用途:带默认值的字典,避免 KeyError
示例

from collections import defaultdict
d = defaultdict(int)  # 默认值为0
d["a"] += 1  # 不需要初始化键

3. deque(双端队列)

用途:高效的头尾插入/删除(比 list 快)。
示例

from collections import deque
q = deque([1, 2, 3])
q.appendleft(0)  # 左侧插入
q.pop()          # 右侧删除

4. namedtuple

用途:创建具有字段名的轻量级元组(类似简易类)。
示例

from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2)  # p.x = 1, p.y = 2

5. OrderedDict(Python 3.7+ 后内置 dict 已有序)

用途:保留键的插入顺序(Python 3.6 之前需要用它保证顺序)。
示例

from collections import OrderedDict
od = OrderedDict([("a", 1), ("b", 2)])

6. ChainMap

用途:合并多个字典,查找时按顺序搜索。
示例

from collections import ChainMap
dict1 = {"a": 1}
dict2 = {"b": 2}
chain = ChainMap(dict1, dict2)  # chain["a"] → 1

7. UserDict / UserList / UserString

用途:用于继承并自定义字典、列表、字符串的行为(不常用)。


何时使用 collections

  • 需要高效统计频率 → Counter
  • 避免字典的 KeyErrordefaultdict
  • 频繁头尾操作 → deque
  • 需要具名字段 → namedtuple
  • 兼容旧版 Python 的字典顺序 → OrderedDict
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值