Python下封裝個好用計數字典包

在Py下要用到計數字典時會發現,標準庫裏沒有現成計數字典類

Py文檔指引裏給出用defaultdict類實現計數字典的方案。給出的例子:

>>> s = 'mississippi'

>>> d = defaultdict(int)

>>> for k in s:

...    d[k] += 1

...

>>> sorted(d.items())

[('i', 4), ('m', 1), ('p', 2), ('s', 4)]

字面意思看着並不一目瞭然

這樣用沒有簡潔直觀設置起點值的寫法

也不方便用到複雜點的數據結構裏,例如:{'a': {'x': 計數值, 'y': 計數值, 'z': 計數值}, 'b': {'x': 計數值, 'y': 計數值, 'z': 計數值}, 'c': {'x': 計數值, 'y': 計數值, 'z': 計數值}}

計數字典類型我這工作裏不少處用到,封裝個吧

用例如下:

>>> accumulated = count_dict()

>>> accumulated['x'] += 9

>>> accumulated.items()

dict_items([('x', 9)])

>>> accumulated = count_dict(10)    #設置起點值

>>> accumulated['x'] += 9

>>> accumulated.items()

dict_items([('x', 19)])

>>> accumulated = defaultdict(count_dict)    #可以在defaultdict裏像基礎類型一樣使用

>>> accumulated['x']['y'] += 9

>>> {'x': dict(accumulated['x'])}

{'x': {'y': 9}}

>>> accumulated = defaultdict(count_dict(10))

>>> accumulated['x']['y'] += 9

>>> {'x': dict(accumulated['x'])}

{'x': {'y': 19}}

這下簡潔了

已經發布到了PyPI上,可以很方便的安裝分發了

pip install count-dict

程序裏引用:

from count_dict_package import count_dict

源碼在GitHub

GitHub - fsssosei/count_dict: This is a Python package for count dictionaries

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章