Python OrderedDict 实现 Least Recently used(LRU)缓存

OrderedDict 实现 Least Recently used(LRU)缓存

引言

LRU 缓存是一种缓存替换策略,当缓存空间不足时,会移除最久未使用的数据以腾出空间存放新的数据。LRU 缓存的特点:

  1. 有限容量:缓存拥有固定的容量,当容量满时,需要移除旧数据。
  2. 淘汰策略:将最久未使用的缓存项移除。
  3. 快速访问:访问,插入,删除的复杂度位 O(1)。

本文将介绍 OrderedDict 实现 Least Recently used(LRU)缓存的方法。

正文

python 复制代码
from collections import OrderedDict


class LRUCache:
    def __init__(self, capacity: int):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key: str) -> int:
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key: str, value: int) -> None:
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)


if __name__ == '__main__':
    lru = LRUCache(2)
    lru.put('a', 1)
    lru.put('b', 2)
    print(lru.get('a'))  # 1
    lru.put('c', 3)
    print(lru.get('b'))  # -1

当使用 print(lru.get('a')) 语句输出结果时,键值对 'a':1 会被放在 OrderedDict 最后的位置,lru.put('c', 3) 会导致位于开始位置的元素 'b':2 被删除。当我们再次使用 print(lru.get('b')) 访问 'b':2 元素时会得到返回值 -1 提示我们当前缓存中已经不存在该元素。

如果大家觉得有用,就点个赞让更多的人看到吧~

相关推荐
剑穗挂着新流苏31227 分钟前
117_PyTorch 实战:利用训练好的模型进行单张图片验证
人工智能·python·深度学习
lars_lhuan1 小时前
从键值数据库到Redis
数据库·redis·缓存
Lethehong1 小时前
Python Selenium全栈指南:从自动化入门到企业级实战
python·selenium·测试工具·自动化
智算菩萨1 小时前
MP3音频编码原理深度解析与Python全参数调优实战:从心理声学模型到LAME编码器精细控制
android·python·音视频
qq_452396232 小时前
【模型手术室】第四篇:全流程实战 —— 使用 LLaMA-Factory 开启你的第一个微调任务
人工智能·python·ai·llama
无心水3 小时前
Java时间处理封神篇:java.time全解析
java·开发语言·python·架构·localdate·java.time·java时间处理
吴秋霖3 小时前
【某音电商】protobuf聊天协议逆向
python·算法·protobuf
深藏功yu名3 小时前
Day24:向量数据库 Chroma_FAISS 入门
数据库·人工智能·python·ai·agent·faiss·chroma
cm6543203 小时前
用Python破解简单的替换密码
jvm·数据库·python
wan9yu4 小时前
为什么你需要给 LLM 的数据"加密"而不是"脱敏"?我写了一个开源工具
python