Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add or increment single item of the Python Counter class

Tags:

python

counter

A set uses .update to add multiple items, and .add to add a single one.

Why doesn't collections.Counter work the same way?

To increment a single Counter item using Counter.update, it seems like you have to add it to a list:

from collections import Counter  c = Counter() for item in something:     for property in properties_of_interest:         if item.has_some_property: # simplified: more complex logic here             c.update([item.property])         elif item.has_some_other_property:             c.update([item.other_property])         # elif... etc 

Can I get Counter to act like set (i.e. eliminate having to put the property in a list)?

Use case: Counter is very nice because of its defaultdict-like behavior of providing a default zero for missing keys when checking later:

>>> c = Counter() >>> c['i'] 0 

I find myself doing this a lot as I'm working out the logic for various has_some_property checks (especially in a notebook). Because of the messiness of that, a list comprehension isn't always desirable etc.

like image 363
scharfmn Avatar asked May 02 '15 11:05

scharfmn


People also ask

How do you add a single to a count in Python?

In python, if you want to increment a variable we can use “+=” or we can simply reassign it “x=x+1” to increment a variable value by 1. After writing the above code (python increment operators), Ones you will print “x” then the output will appear as a “ 21 ”. Here, the value of “x” is incremented by “1”.

How do you update a counter in Python?

Python updating counter We can add values to the counter by using update() method.

What does counter () do in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.

How do I extract a value from 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.


1 Answers

Well, you don't really need to use methods of Counter in order to count, do you? There's a += operator for that, which also works in conjunction with Counter.

c = Counter() for item in something:     if item.has_some_property:         c[item.property] += 1     elif item.has_some_other_property:         c[item.other_property] += 1     elif item.has_some.third_property:         c[item.third_property] += 1 
like image 84
shx2 Avatar answered Sep 22 '22 13:09

shx2