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 提示我们当前缓存中已经不存在该元素。

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

相关推荐
程序员爱钓鱼9 分钟前
Python编程实战:面向对象与进阶语法——类型注解与代码规范(PEP 8)
后端·python·ipython
程序员爱钓鱼9 分钟前
Python实战:用高德地图API批量获取地址所属街道并写回Excel
后端·python·ipython
reasonsummer1 小时前
【教学类-97-06】20251105“葡萄”橡皮泥黏贴(小班主题《苹果与橘子》)
python
卖个几把萌2 小时前
【16】Selenium+Python 接管已打开谷歌浏览器
python·selenium·测试工具
像风一样的男人@2 小时前
python --两个文件夹文件名比对(yolo 图和label标注比对检查)
windows·python·yolo
lllsure3 小时前
【Python】Dict(字典)
开发语言·python
tianyuanwo3 小时前
Rust开发完全指南:从入门到与Python高效融合
开发语言·python·rust
如何原谅奋力过但无声4 小时前
TensorFlow 2.x常用函数总结(持续更新)
人工智能·python·tensorflow
程序员-小李4 小时前
基于 Python + OpenCV 的人脸识别系统开发实战
开发语言·python·opencv
万粉变现经纪人4 小时前
如何解决 pip install 安装报错 [WinError 32] 文件被占用(杀毒/占用进程)问题
python·pycharm·flask·beautifulsoup·bug·pandas·pip