bahmait bahmait - 5 months ago 14
Python Question

Python Counter class: add or increment single item

To increment a single item in collections.Counter, you have to add it to a list to use

Counter.update
.

c = Counter()

for item in something:
for property in properties_of_interest:
if item.has_some_property: # pseudocode: more complex logic here
c.update([item.property])
elif item.has_some_other_property:
c.update([item.other_property])
# elif... etc


A
set
uses
.update
to add multiple items, and
add
to add a single one. Why doesn't
Counter
work the same way? Can I get it to act similarly (i.e. eliminate having to put the property in a list)?

Imagine case where you have some unknown objects, and you're trying many different things quickly to find out some preliminary things about them: performance and scaling don't matter, and a comprehension would make adding and subtracting logic time-consuming.

Answer

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