如何解决从 LRU Cache 打印值并在一段时间后删除值时遇到的问题?

How to solve issue faced when printing value from a LRU Cache and deleting values after a period of time?

我一直在尝试实现我自己的 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

但对于这种情况,它 return 是一个错误:

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

然而,即使我进行了更改,当我尝试 'get' 值时,它们也不会 return -1 当它超过到期时间时。我该如何解决这个问题?

为什么它不适用于这种情况,我如何让它打印我的预期输出?

您的 cache 对象出现错误 object is not iterable 因为您还没有实现任何使其可迭代的方法。

这也许最好留给另一个问题:Build a Basic Python Iterator

引自this answer

There are four ways to build an iterative function:

  • ...
  • ...
  • create an iterator (defines __iter__ and __next__ (or next in Python 2.x))
  • create a function that Python can iterate over on its own (defines __getitem__)

根据我的更改,当我尝试 'get' 值时,它们不会 return -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 永远不会改变。
    • and(一旦定义了 expires_at)将只是 return True