Search code examples
python-3.xcounter

Counter sum filtered counts


The result should sum over a counter like counter.total(), but only on certain elements in the counter. The elements should be filtered by their keys, I would imagine something like the following code existed:

sum(counter_element.count() for counter_element in counter.elements() if counter_element.key() is good)

How to achieve the correct result?

tried this with counter.elements(), counter.items() and counter.values() but no combination of functions did the job.


Solution

  • sum(count for (key, count) in counter.items() if key is good)
    

    does the job. The main idea is that .items() returns the tuples and (key, count) then already holds the correct objects one can be interested in.