Python面试题:在 Python 中,如何实现一个 LRU(最近最少使用)缓存?
创始人
2025-01-11 08:03:09
0

在 Python 中,可以使用 collections.OrderedDictfunctools.lru_cache 来实现一个 LRU(最近最少使用)缓存。functools.lru_cache 是一个内置装饰器,可以直接用于缓存函数的结果。而如果你想实现一个自定义的 LRU 缓存,可以使用 collections.OrderedDict

下面是使用 collections.OrderedDict 实现一个简单的 LRU 缓存的示例:

from collections import OrderedDict  class LRUCache:     def __init__(self, capacity: int):         self.cache = OrderedDict()         self.capacity = capacity      def get(self, key: int) -> int:         if key not in self.cache:             return -1         else:             self.cache.move_to_end(key)  # 将访问的key移动到末尾             return self.cache[key]      def put(self, key: int, 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)  # 弹出最左侧(最旧)的元素  # 使用示例 lru_cache = LRUCache(2) lru_cache.put(1, 1) lru_cache.put(2, 2) print(lru_cache.get(1))  # 返回 1 lru_cache.put(3, 3)      # 移除键 2 print(lru_cache.get(2))  # 返回 -1 (未找到) lru_cache.put(4, 4)      # 移除键 1 print(lru_cache.get(1))  # 返回 -1 (未找到) print(lru_cache.get(3))  # 返回 3 print(lru_cache.get(4))  # 返回 4 

在这个实现中,LRUCache 类使用 OrderedDict 来保持插入元素的顺序。put 方法在插入新元素时,如果超过容量限制,则移除最旧的元素。get 方法在访问元素时,将其移动到末尾,以表示最近访问。

此外,如果你希望更方便地使用 LRU 缓存,可以直接使用 functools.lru_cache 装饰器。以下是一个示例:

from functools import lru_cache  @lru_cache(maxsize=2) def some_expensive_function(n):     print(f"Computing {n}")     return n * n  # 使用示例 print(some_expensive_function(2))  # 输出 "Computing 2" 和 4 print(some_expensive_function(3))  # 输出 "Computing 3" 和 9 print(some_expensive_function(2))  # 直接输出 4,不会打印 "Computing 2" print(some_expensive_function(4))  # 输出 "Computing 4" 和 16 print(some_expensive_function(3))  # 再次计算 3,因为之前的结果已被移除 

使用 lru_cache 装饰器,可以轻松为函数添加缓存功能,并且不需要手动管理缓存的逻辑。maxsize 参数指定了缓存的最大容量。

相关内容

热门资讯

2分钟私人局!竞技联盟辅助,a... 2分钟私人局!竞技联盟辅助,aapoker有脚本吗,辅助教程(存在有挂)-哔哩哔哩aapoker有脚...
第5些了解!蜀山四川破解版安卓... 第5些了解!蜀山四川破解版安卓版,WePOker有没有透视方法,必胜教程(确实有挂)1、蜀山四川破解...
第十分钟了解(Wepoke教程... 第十分钟了解(Wepoke教程)外挂辅助app(辅助挂)实用技巧(2021已更新)(哔哩哔哩);一、...
第三分钟了解“随意玩透视辅助”... 第三分钟了解“随意玩透视辅助”详细透视开挂辅助脚本-哔哩哔哩;小薇(透视辅助)致您一封信;亲爱随意玩...
五分钟私人局!aapoker破... 五分钟私人局!aapoker破解侠是真的吗,wepoker游戏安装教程,AA德州教程(有挂技术)-哔...
第2瞬间了解!指尖四川辅助脚本... 第2瞬间了解!指尖四川辅助脚本视频,拱趴大菠萝有挂吗,wpk教程(有挂方法)第2瞬间了解!指尖四川辅...
第四分钟了解(鸿运阁)外挂辅助... 第四分钟了解(鸿运阁)外挂辅助app(辅助挂)攻略方法(2025已更新)(哔哩哔哩);1、超多福利:...
第七分钟了解“赣牌圈挂安装图解... 第七分钟了解“赣牌圈挂安装图解”详细透视开挂辅助教程-哔哩哔哩;赣牌圈挂安装图解免费下载原版,在赣牌...
5分钟指导!wepoker辅助... 5分钟指导!wepoker辅助器免费,pokemmo手机版透视脚本,科技教程(有挂规律)-哔哩哔哩1...
第3瞬间了解!九游破解辅助插件... 第3瞬间了解!九游破解辅助插件hhpoker,aapoker脚本,力荐教程(有挂工具)1、玩家可以在...