Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "Counter" in Python 3.2

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.

like image 817
AlphaTested Avatar asked Jun 19 '11 04:06

AlphaTested


People also ask

How do you use counters in python?

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.

Is counter faster than dict?

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.

How do I get an item of a counter in python?

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.

What library is counter in python?

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.


2 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.

like image 179
hobbs Avatar answered Sep 24 '22 06:09

hobbs


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}) 
like image 43
jagadesh Avatar answered Sep 22 '22 06:09

jagadesh