duh*_*ime 5 python dictionary data-structures
我打算从磁盘读取数百万个小文件。为了最小化 i/o,我计划使用一个将文件路径映射到其内容的字典。我只希望字典保留插入其中的最后 n 个键(因此字典将充当缓存)。
Python 中是否有数据结构已经实现了这种行为?我想在重新发明轮子之前检查一下。
使用collections.dequemaxlen 为 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)
Run Code Online (Sandbox Code Playgroud)
对于我的特定问题,由于我需要从磁盘读取文件,我想我将按照 @PatrickHaugh 的建议使用 lru 缓存。这是使用缓存的一种方法:
from functools import lru_cache
@lru_cache(maxsize=10)
def read_file(file_path):
print(' * reading', file_path)
return file_path # update to return the read file
for i in range(100):
if i % 2 == 0:
i = 0 # test that requests for 0 don't require additional i/o
print(' * value of', i, 'is', read_file(i))
Run Code Online (Sandbox Code Playgroud)
输出显示对 0 的请求不会产生额外的 I/O,这是完美的。