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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值