python字典计数_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
源碼在GitHubfsssosei/count_dict?github.com
總結
以上是生活随笔為你收集整理的python字典计数_Python下封装个好用计数字典包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 撒拉嘿呦是什么意思
- 下一篇: 想念一个人的心情短语,句句暖心,甜到心坎