如何使用Python中的collections模块提供的数据结构,如deque、Counter、OrderedDict等

Python 的 collections 模块提供了一些额外的数据结构,这些数据结构在内置的数据类型(如列表、字典、集合等)的基础上,增加了额外的功能或优化了性能。下面是如何使用 collections 模块中的 dequeCounterOrderedDict 这三种数据结构的简单示例。

1. deque(双端队列)

deque(发音为"deck")是一个线程安全、快速添加/删除元素于两端的线性容器。它支持从两端快速添加和删除元素,时间复杂度为 O(1)。

复制代码

python复制代码

|---|--------------------------------------------------------------|
| | from collections import deque |
| | |
| | # 创建一个 deque |
| | d = deque('ghi') |
| | |
| | # 添加元素到右端 |
| | d.append('j') |
| | d.append('k') |
| | |
| | # 添加元素到左端 |
| | d.appendleft('f') |
| | d.appendleft('e') |
| | |
| | # 打印 deque |
| | print(d) # 输出: deque(['e', 'f', 'g', 'h', 'i', 'j', 'k']) |
| | |
| | # 从右端移除元素 |
| | print(d.pop()) # 输出: 'k' |
| | |
| | # 从左端移除元素 |
| | print(d.popleft()) # 输出: 'e' |

2. Counter(计数器)

Counter 是一个字典子类,用于计数可哈希对象。它是一个字典,其中元素被当作字典键,它们的计数被存储为字典值。

复制代码

python复制代码

|---|---------------------------------------------------------------------------------------------|
| | from collections import Counter |
| | |
| | # 创建一个 Counter |
| | c = Counter('gallahad') |
| | |
| | # 输出 Counter |
| | print(c) # 输出: Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1}) |
| | |
| | # 更新计数器 |
| | c.update('admiral') |
| | |
| | # 输出更新后的 Counter |
| | print(c) # 输出: Counter({'a': 4, 'd': 2, 'l': 2, 'g': 1, 'm': 1, 'i': 1, 'r': 1, 'h': 1}) |
| | |
| | # 获取某个元素的计数 |
| | print(c['a']) # 输出: 4 |
| | |
| | # 获取元素计数并删除该元素(如果计数为 0,则不执行删除) |
| | print(c.pop('d')) # 输出: 2 |
| | |
| | # 输出更新后的 Counter |
| | print(c) # 输出: Counter({'a': 4, 'l': 2, 'g': 1, 'm': 1, 'i': 1, 'r': 1, 'h': 1}) |

3. OrderedDict(有序字典)

OrderedDict 是一个字典子类,它保持了元素被插入时的顺序。当迭代 OrderedDict 时,元素的顺序与它们被插入时的顺序相同。

复制代码

python复制代码

|---|----------------------------------------|
| | from collections import OrderedDict |
| | |
| | # 创建一个 OrderedDict |
| | d = OrderedDict() |
| | d['foo'] = 1 |
| | d['bar'] = 2 |
| | d['spam'] = 3 |
| | d['grok'] = 4 |
| | |
| | # 迭代并打印 OrderedDict |
| | for key in d: |
| | print(key, d[key]) |
| | # 输出: |
| | # foo 1 |
| | # bar 2 |
| | # spam 3 |
| | # grok 4 |
| | |
| | # 插入一个新的键值对到有序字典的开始 |
| | d.move_to_end('foo', last=False) |
| | |
| | # 再次迭代并打印 |
| | for key in d: |
| | print(key, d[key]) |
| | # 输出: |
| | # foo 1 |
| | # bar 2 |
| | # spam 3 |
| | # grok 4 |

这些数据结构在需要特定功能的场景下非常有用,如需要维护插入顺序的字典、需要快速从两端添加/删除元素的列表,或者需要计数可哈希对象的场景。

相关推荐
孟健2 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞4 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽6 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程10 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪11 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook11 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python