在Python 3.2中使用"Counter"

Alp*_*ted 19 python python-3.x

我一直在尝试Counter在Python 3.2中使用该方法,但我不确定我是否正确使用它.知道我为什么会收到这个错误吗?

>>> import collections
>>> Counter()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    Counter()
NameError: name 'Counter' is not defined
Run Code Online (Sandbox Code Playgroud)

我可以访问Counterif if go collections.Counter(),但不能访问文档中的示例.

hob*_*bbs 34

你想要的from collections import Counter.使用import collections仅使集合中的东西可用作集合.东西.有关本教程章节import前几节中的模块和工作原理的更多信息.


小智 7

使用 Counter 尝试一下它工作正常

import collections
print collections.Counter(['a','b','c','a','b','b'])
Run Code Online (Sandbox Code Playgroud)

输出:

Counter({'b': 3, 'a': 2, 'c': 1})
Run Code Online (Sandbox Code Playgroud)

  • 标题是“在 Python 3.2 中使用计数器”。这对已接受的答案有何补充?请阅读[如何写出一个好的答案?](https://stackoverflow.com/help/how-to-answer) (2认同)