在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
网友评论