【问题标题】:from collections import defaultdict从集合导入 defaultdict
【发布时间】:2020-09-17 21:16:57
【问题描述】:

为什么当我没有将 defaultdictdefault value 设置为零 (int) 时,我下面的程序没有给我结果:

>>> doc
'A wonderful serenity has taken possession of my entire soul, like these sweet mornings of spring which I enjoy with my whole heart. I am alone, and feel the charm of existence in this spot, which was created for the bliss of souls like mine. I am so happy'
>>> some = defaultdict()
>>> for i in doc.split():
...  some[i] = some[i]+1
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 'A'
>>> some
defaultdict(None, {})
>>> i
'A'

但它适用于默认值

>>> some = defaultdict(int)
>>> for i in doc.split():
...  some[i] = some[i]+1
...
>>> some
defaultdict(<class 'int'>, {'A': 1, 'wonderful': 1, 'serenity': 1, 'has': 1, 'taken': 1, 'possession': 1, 'of': 4, 'my': 2, 'entire': 1, 'soul,': 1, 'like': 2, 'these': 1, 'sweet': 1, 'mornings': 1, 'spring': 1, 'which': 2, 'I': 3, 'enjoy': 1, 'with': 1, 'whole': 1, 'heart.': 1, 'am': 2, 'alone,': 1, 'and': 1, 'feel': 1, 'the': 2, 'charm': 1, 'existence': 1, 'in': 1, 'this': 1, 'spot,': 1, 'was': 1, 'created': 1, 'for': 1, 'bliss': 1, 'souls': 1, 'mine.': 1, 'so': 1, 'happy': 1})
>>>

你能说出为什么会这样吗?

【问题讨论】:

    标签: python dictionary collections defaultdict


    【解决方案1】:

    正如文档所说:

    第一个参数提供default_factory 的初始值 属性;默认为None。所有剩余的参数都被处理 就像它们被传递给 dict 构造函数一样,包括 关键字参数。

    因此,如果你只写defaultdict而不向构造函数传递任何值,则默认值设置为None 查看输出:

    some = defaultdict()
    print(some)    # defaultdict(None, {}) 
    

    并且当值设置为None时,不能执行:some[i] = some[i]+1
    因此,您必须将默认值显式设置为 intsome = defaultdict(int)

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 2019-05-13
      • 2020-04-30
      • 1970-01-01
      相关资源
      最近更新 更多