【问题标题】:python better way to set dictionary value [closed]python设置字典值的更好方法[关闭]
【发布时间】:2021-09-06 02:58:35
【问题描述】:

在python中有什么更好的方法来做到这一点 当前 = {}

    if key in current:
        current[key] += 1
    else:
        current[key] = 1

感谢您的帮助

【问题讨论】:

标签: python python-3.x dictionary


【解决方案1】:

使用 defaultdict 比内置 dict 功能有一些优势。一方面,使用一次查找而不是两次查找来执行这种类型的未初始化增量更有效。

from collections import defaultdict
current = defaultdict(int)
current[key] += 1

另一方面,使用 dict,无论您如何编写它,您仍然需要单独查找 get 然后设置。

【讨论】:

    【解决方案2】:

    使用setdefault:

    current = {}
    a = ['a', 'b', 'a']
    for i in a:
        current[i] = current.setdefault(i, 0) + 1
    print(current)
    

    输出:

    {'a': 2, 'b': 1}
    

    或者使用get:

    current = {}
    a = ['a', 'b', 'a']
    for i in a:
        current[i] = current.get(i, 0) + 1
    

    或者如果你想获得频率计数:

    from collections import Counter
    a = ['a', 'b', 'a']
    current = Counter(a)
    print(current)
    

    输出:

    Counter({'a': 2, 'b': 1})
    

    【讨论】:

      【解决方案3】:

      这里是这个代码,defaultdict(int) 会在 key 不存在时添加一个默认值:

      from collections import defaultdict
      current = defaultdict(int)
      
      keys = ['a','b', 'c', 'a']
      
      for key in keys:
          current[key]+=1
      print (current)
          
      

      输出:

      defaultdict(<class 'int'>, {'a': 2, 'b': 1, 'c': 1})
      

      Here 是关于 defaultdict 行为及其实现方式的好文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-24
        • 1970-01-01
        • 2015-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多