在Python 3.2中使用“Counter”

时间:2011-06-19 04:27:53

标签: python python-3.x

我一直在尝试在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(),但不能访问文档中的示例。

2 个答案:

答案 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})