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.
Initializing. Counter supports three forms of initialization. Its constructor can be called with a sequence of items, a dictionary containing keys and counts, or using keyword arguments mapping string names to counts. To create an empty counter, pass the counter with no argument and populate it via the update method.
Python - Counter(faster than 50%) and defaultdict(faster than 98%) Increment dictionary values for each character in s, then decrement for t. if all values at the end are zeros. both strings are valid Anagrams.
Accessing Elements in Python Counter To get the list of elements in the counter we can use the elements() method. It returns an iterator object for the values in the Counter.
A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts.
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With