python缓存字典 - 计算命中数

duc*_*cin 5 python caching dictionary count

我正在用 python 实现一个缓存服务。到目前为止,我正在使用一个简单的字典。我想要做的是计算点击次数(键检索存储值的次数)。Python 内置 dict 没有这种可能性(据我所知)。我搜索了“python字典计数”并找到了Counter(也在stackoverflow上),但我猜这不满足我的要求。我不需要计算已经存在的东西。我需要增加来自外部的东西。而且我认为存储另一个只包含点击次数的字典并不是我能得到的最好的数据结构:)

你有什么想法如何有效地做到这一点吗?

fre*_*ish 5

您可以对内置dict类进行子类化:

class CustomDict(dict):
    def __init__(self, *args, **kwargs):
        self.hits = {}
        super(CustomDict, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        if key not in self.hits:
            self.hits[key] = 0
        self.hits[key] += 1
        return super(CustomDict, self).__getitem__(key)
Run Code Online (Sandbox Code Playgroud)

用法:

>>> d = CustomDict()
>>> d["test"] = "test"
>>> d["test"]
'test'
>>> d["test"]
'test'
>>> d.hits["test"]
2
Run Code Online (Sandbox Code Playgroud)


F.X*_*.X. 5

对于另一种方法,如果您使用的是 Python 3(或者愿意将此模块添加到您的 Python 2 项目中,它的界面略有不同),我强烈推荐lru_cache装饰器。

请参阅此处的文档。例如,此代码:

from functools import lru_cache

@lru_cache(maxsize=32)
def meth(a, b):
    print("Taking some time", a, b)
    return a + b

print(meth(2, 3))
print(meth(2, 4))
print(meth(2, 3))
Run Code Online (Sandbox Code Playgroud)

...将输出:

Taking some time 2 3
5
Taking some time 2 4
6
5   <--- Notice that this function result is cached
Run Code Online (Sandbox Code Playgroud)

根据文档,您可以使用 获取命中和未命中数meth.cache_info(),并使用 清除缓存meth.cache_clear()


Bi *_*ico 3

使用另一个字典来存储命中计数可能不是一个坏选择,但您也可以执行以下操作:

class CacheService(object):

    def __init__(self):
        self.data = {}

    def __setitem__(self, key, item):
        self.data[key] = [item, 0]

    def __getitem__(self, key):
        value = self.data[key]
        value[1] += 1
        return value[0]

    def getcount(self, key):
        return self.data[key][1]
Run Code Online (Sandbox Code Playgroud)

你可以像这样使用它:

>>> cs = CacheService()
>>> cs[1] = 'one'
>>> cs[2] = 'two'
>>> print cs.getcount(1)
0
>>> cs[1]
'one'
>>> print cs.getcount(1)
1
Run Code Online (Sandbox Code Playgroud)