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.
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”.
Python updating counter We can add values to the counter by using update() method.
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.
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.
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
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