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

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

相关推荐
刘科领1 分钟前
使用ollama & openweb-ui 本地搭建自己的AI
人工智能·python·ui·ai
专业程序开发源3 分钟前
flask家电故障预测系统92491-计算机课程设计/毕业设计
vscode·python·sql·算法·flask·课程设计
夜雪一千4 分钟前
Python 生成模拟地址数据:Faker之外的备选库
网络·windows·python
半亩码田10 分钟前
C#转Python第4.8篇:正则表达式:Python re 模块 vs C# System.Text.RegularExpressions
python·正则表达式·c#
夜雪一千11 分钟前
如何取消PyCharm自动识别test开头文件并进入测试模式
ide·python·pycharm
yi01128 分钟前
LeetCode 643. 子数组最大平均数 I|从暴力枚举到滑动窗口
人工智能·笔记·python·算法·leetcode·滑动窗口
小李不困还能学31 分钟前
PyCharm远程开发连接失败排查与解决
ide·python·pycharm
pride.li31 分钟前
Python 安装
linux·python·ubuntu
全栈练习生42 分钟前
模型上下文协议(MCP)
python·ai
泡海椒1 小时前
JQuick-Excel 多字段 TRANSFORM:让当前行字段、JContext 与展示列各归其位
开发语言·python·excel