python - Python:仅保留最后 n 个插入键的字典
问题描述
我打算从磁盘读取数百万个小文件。为了最小化 i/o,我计划使用将文件路径映射到其内容的字典。不过,我只希望字典保留插入其中的最后 n 个键(因此字典将充当缓存)。
Python 中是否存在已经实现此行为的数据结构?我想在重新发明轮子之前检查一下。
解决方案
用于collections.deque
此,maxlen 为 6,以便它仅存储最后 6 个元素并将信息存储为键值对
from collections import deque
d = deque(maxlen=6)
d.extend([(1,1),(2,2),(3,3),(4,4), (5,5), (6,6)])
d
# deque([(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)], maxlen=6)
d.extend([(7,7)])
d
# deque([(2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7)], maxlen=6)
推荐阅读
- php - 如何从时间戳打印用户的非活动时间?
- firebird - 尝试从 pascal 执行查询时出现异常
- azure-blob-storage - 使用 PowerApps AzureServiceBus 连接器 SendMessage ContentData
- excel - AllowEditRange 重新保护
- java - 是否可以以更紧凑的方式将多个字符串声明为方法的参数?
- c# - Windows.Management.Deployment.PackageManager - 在桌面应用程序中返回 ComObject
- flutter - 将值从子级传递给父级,然后重建状态
- vba - VBA在word中添加一个宏到鼠标右键
- amazon-web-services - AWS S3 预签名 url - 下载文件得到 403
- python - 在 Python 中扫描文件夹和子文件夹并移动具有相同文件夹结构的文件