从集合导入defaultdict

2024-09-28 03:20:27 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么我没有将defaultdict默认值设置为零(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})
>>>

你能告诉我为什么它是这样工作的吗?


Tags: oftheinwhichfordocmysome
1条回答
网友
1楼 · 发布于 2024-09-28 03:20:27

正如文件所说:

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

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

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

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

相关问题 更多 >

    热门问题