我想缓存一个将列表作为参数的函数,但是当我尝试使用 functools.lru_cache
这样做时装饰器,它失败并显示 TypeError: unhashable type: 'list'
。
import functools
@functools.lru_cache()
def example_func(lst):
return sum(lst) + max(lst) + min(lst)
print(example_func([1, 2]))
最佳答案
这失败了,因为列表是不可散列的。这将使 Python 很难知道缓存了哪些值。解决此问题的一种方法是在将列表传递给缓存函数之前将列表转换为元组:由于元组不可变且可散列,因此可以缓存它们。
长话短说
使用元组代替列表:
>>> @lru_cache(maxsize=2)
... def my_function(args):
... pass
...
>>> my_function([1,2,3])
Traceback (most recent call last):
File "<input>", line 1, in <module>
my_function([1,2,3])
TypeError: unhashable type: 'list'
>>> # TO FIX: use a tuple
>>> my_function(tuple([1,2,3]))
>>>
关于Python3 传递列表以使用 functools.lru_cache 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210801/