Using "Counter" in Python 3.2
Question:
I’ve been trying to use the Counter
method in Python 3.2 but I’m not sure if I’m using it properly. Any idea why I’m getting the error?
>>> import collections
>>> Counter()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
Counter()
NameError: name 'Counter' is not defined
I can access the Counter
if I go collections.Counter()
, but not the examples in the documentation.
Answers:
You want from collections import Counter
. Using import collections
only makes the stuff in collections available as collections.something. More on modules and the workings of import
in the first few sections of this tutorial chapter.
Try this its working fine using Counter
import collections
print collections.Counter(['a','b','c','a','b','b'])
Output:
Counter({'b': 3, 'a': 2, 'c': 1})
I’ve been trying to use the Counter
method in Python 3.2 but I’m not sure if I’m using it properly. Any idea why I’m getting the error?
>>> import collections
>>> Counter()
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
Counter()
NameError: name 'Counter' is not defined
I can access the Counter
if I go collections.Counter()
, but not the examples in the documentation.
You want from collections import Counter
. Using import collections
only makes the stuff in collections available as collections.something. More on modules and the workings of import
in the first few sections of this tutorial chapter.
Try this its working fine using Counter
import collections
print collections.Counter(['a','b','c','a','b','b'])
Output:
Counter({'b': 3, 'a': 2, 'c': 1})