27

使用 python 3.2。

import collections
d = defaultdict(int)

NameError: name 'defaultdict' is not defined

我重新启动了空闲。我知道正在导入集合,因为正在输入

collections

结果是

<module 'collections' from '/usr/lib/python3.2/collections.py'>

help(collections) 还向我显示了包括 defaultdict 类的帮助。

我究竟做错了什么?

4

4 回答 4

39
>>> import collections
>>> d = collections.defaultdict(int)
>>> d
defaultdict(<type 'int'>, {})

您可能应该阅读import声明

于 2013-07-20T21:57:45.147 回答
37

你不是在导入defaultdict. 执行以下任一操作:

from collections import defaultdict

或者

import collections
d = collections.defaultdict(list)
于 2013-07-20T21:57:46.143 回答
9

你需要写:

from collections import defaultdict
于 2014-06-03T10:46:49.720 回答
0

Defaultdict 是一个容器,类似于模块集合中存在的字典。要访问 defaultdict,您必须将您的导入语句修改为 -

from collections import defaultdict

或使用 -

import collections
d = collections.defaultdict(int)

能够使用 defaultdict

于 2021-02-12T08:20:13.980 回答