defaultdict未定义。

30

使用Python 3.2版本。

import collections
d = defaultdict(int)

运行

NameError: name 'defaultdict' is not defined

我已经重新启动了Idle。我知道正在导入collections,因为输入

collections

导致结果

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

同时help(collections)向我展示了包括defaultdict类的帮助信息。

我做错了什么?


1
阅读有关“导入”的内容。它只会将您指定的名称添加到您的命名空间中。例如,您可以使用from collections import defaultdict,或者您可以将defaultdict称为collections.defaultdict - Kyle Strand
1
这里的帖子让你觉得那会起作用?也许如果有些答案忘记使用正确的导入语句,它可以被纠正。 - Martijn Pieters
4个回答

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

你可能会受益于阅读有关import语句的内容。


42

您没有导入defaultdict。请执行以下任一操作:

from collections import defaultdict
或者
import collections
d = collections.defaultdict(list)

9
您需要编写代码:
from collections import defaultdict

0

Defaultdict是一个类似于模块collections中字典的容器。要访问defaultdict,您需要修改导入语句为 -

from collections import defaultdict

或者使用 -

import collections
d = collections.defaultdict(int)

为了能够使用defaultdict


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接