在Python 3.2中使用"Counter

31 投票
2 回答
56310 浏览
提问于 2025-04-16 19:50

我一直在尝试在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

如果我直接使用collections.Counter(),我可以访问Counter,但文档中的例子却不能用。

2 个回答

7

试试这个,使用Counter可以很好地工作。

import collections
print collections.Counter(['a','b','c','a','b','b'])

输出结果:

Counter({'b': 3, 'a': 2, 'c': 1})
55

你需要用 from collections import Counter 这行代码。使用 import collections 只会让 collections 里的东西以 collections.某个东西 的形式出现。关于模块和 import 的工作原理,可以在这个教程章节的前几部分找到更多信息。

撰写回答