I have Counter
(from collections
) and you want to filter out a set of unwanted elements. The result should be a new counter (or, if you want, do it in place) containing only elements that do not match the property. I tried using filter
in Counter
, but the result is no longer Counter
, but just list
. I also tried to subtract a set
unwanted elements from this Counter
, but this operation is not implemented. Subtracting Counter
works, but I donβt have a second Counter
, and creating it is essentially the same task that I am trying to accomplish.
Counter([ 1,2,3,4,5,6,7,6,5,4,3,2,3,4,5,6,5,4,3,4,5,4 ]) β Counter({4: 6, 5: 5, 3: 4, 6: 3, 2: 2, 1: 1, 7: 1})
Now I want to remove all values 2
and 3
from this counter, so the result should be
Counter({4: 6, 5: 5, 6: 3, 1: 1, 7: 1})
Here are my approaches:
filter(lambda x: x not in (2, 3), c) β [1, 4, 5, 6, 7]
But I do not need a list.
c - set([ 2, 3 ]) β TypeError: unsupported operand type(s) for -: 'Counter' and 'set'
I can use sth, which iterates over the unpacked list of items in Counter
as follows:
Counter(x for x in c.elements() if x not in (2, 3)) β Counter({4: 6, 5: 5, 6: 3, 1: 1, 7: 1})
but it is obviously unreasonably expensive for large volumes.
The only (not very pleasant) solution I found is cumbersome:
Counter({ k: v for k, v in c.iteritems() if k not in (2, 3) })
Is there anything better, lighter, more readable that I miss?
Why is there no simple subtraction operator for Counter
that can be used with set
?