我一直在尝试在Python 3.2中使用Counter
方法,但我不确定我是否正确使用它。知道我为什么会收到这个错误吗?
>>> import collections
>>> Counter()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
Counter()
NameError: name 'Counter' is not defined
如果我去Counter
,我可以访问collections.Counter()
,但不能访问文档中的示例。
答案 0 :(得分:33)
你想要from collections import Counter
。使用import collections
仅使集合中的内容可用作集合。某些内容。有关this tutorial chapter前几节中import
的模块和工作方式的更多信息。
答案 1 :(得分:2)
使用Counter
尝试使用它import collections
print collections.Counter(['a','b','c','a','b','b'])
输出:
Counter({'b': 3, 'a': 2, 'c': 1})