bahmait bahmait - 2 years ago 85
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


c = Counter()

for item in something:
for property in properties_of_interest:
if item.has_some_property: # pseudocode: more complex logic here
elif item.has_some_other_property:
# elif... etc

to add multiple items, and
to add a single one. Why doesn't
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 Source

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[] += 1
    elif item.has_some_other_property:
        c[item.other_property] += 1
    elif item.has_some.third_property:
        c[item.third_property] += 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download