我一直在尝试实现我自己的 LRU 缓存版本,该版本会在短时间内删除最近最少使用的值。我正在使用在 ( https://www.kunxi.org/blog/2014/05/lru-cache-in-python/ ) 中找到的代码作为模板。
(这是在那里找到的代码,因此您不必打开它):
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.tm = 0
self.cache = {}
self.lru = {}
def get(self, key):
if key in self.cache:
self.lru[key] = self.tm
self.tm += 1
return self.cache[key]
return -1
def set(self, key, value):
if len(self.cache) >= self.capacity:
# find the LRU entry
old_key = min(self.lru.keys(), key=lambda k:self.lru[k])
self.cache.pop(old_key)
self.lru.pop(old_key)
self.cache[key] = value
self.lru[key] = self.tm
self.tm += 1
这段代码按预期工作
cache = LRUCache(2)
cache.set(1, 20)
cache.set(2, 40)
print(cache.get(2))
40
但对于这种情况,它返回一个错误:
for i in cache:
print(i)
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'LRUCache' object is not iterable
我期望的输出是:
(1, 20)
(2, 40)
为什么它不适用于这种情况以及如何让它打印我的预期输出?
另外,我想自动删除长时间在缓存中的值,我已经尝试过,但无法完成此操作。我尝试修改代码:
from time import time
class LRUCache:
def __init__(self, capacity, expiry_time):
self.capacity = capacity
self.expiry_time = expiry_time
self.expired = False
self.tm = 0
self.cache = {}
self.lru = {}
def get(self, key):
if key in self.cache:
self.lru[key] = self.tm
self.tm += 1
return self.cache[key]
return -1
if self.expired is False:
return (self.expires_at < time())
if self.expires_at < time():
return -1
def set(self, key, value):
if len(self.cache) >= self.capacity:
# find the LRU entry
old_key = min(self.lru.keys(), key=lambda k:self.lru[k])
self.cache.pop(old_key)
self.lru.pop(old_key)
self.cache[key] = value
self.lru[key] = self.tm
self.tm += 1
但是,即使进行了更改,当我尝试“获取”值时,它们在超过到期时间时也不会返回 -1。我该如何解决这个问题?
最佳答案
为什么它不适用于这种情况以及如何让它打印我的预期输出?
您的缓存
对象收到错误对象不可迭代
,因为您尚未实现任何使其可迭代的方法。
这也许最好留给另一个问题:Build a Basic Python Iterator
引用 this answer :
There are four ways to build an iterative function:
- ...
- ...
- create an iterator (defines
__iter__
and__next__
(ornext
in Python 2.x))- create a function that Python can iterate over on its own (defines
__getitem__
)
根据我的更改,当我尝试“获取”值时,它们在超过到期时间后不会返回 -1
对于您的更改,您已将它们放在函数的末尾,因此默认功能始终首先发生。这需要重新排列:
class LRUCache:
def __init__(self, capacity, expiry_time):
...
def get(self, key):
if self.expired is False:
return (self.expires_at < time())
if self.expires_at < time():
return -1
if key in self.cache:
self.lru[key] = self.tm
self.tm += 1
return self.cache[key]
return -1
def set(self, key, value):
...
但是,实现过程中还存在一些其他直接问题:
self.expiry_time
一旦设置就不会被使用或检查。self.expires_at
从未定义。if self.expired is False
:这将始终报告True
,因为expired
永远不会改变。- 并且(一旦定义了
expires_at
)将仅返回True
- 并且(一旦定义了
关于python - 如何解决从 LRU 缓存打印值并在一段时间后删除值时遇到的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794255/