美文网首页
python 字典value实现+=操作

python 字典value实现+=操作

作者: Elvis_zhou | 来源:发表于2019-07-11 11:53 被阅读0次

    通常我们都会需要去实现一个值为int或float的字典,还要实现-=,+=,有没有更加简便的方法呢?
    答案是:肯定有啊!!!

    那就是使用defaultdict

    from collections import defaultdict
    foo = defaultdict(int)
    foo['count'] += 1
    

    在Python> = 2.7中,您还有一个单独的Counter类用于这些目的。对于Python 2.5和2.6,您可以使用其backported version

    参考: How to add or increment a dictionary entry?

    相关文章

      网友评论

          本文标题:python 字典value实现+=操作

          本文链接:https://www.haomeiwen.com/subject/pdurkctx.html