python - Counter with filter or subtract or similar -


i have counter (from collections) , filter out set of unwanted items. result should new counter (or if like, in-place) containing items not matching property. tried using filter on counter result isn't counter anymore mere list. tried subtracting set of unwanted items counter operation isn't implemented. subtracting counter works, don't have second counter , creating same task i'm trying perform.

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 want remove 2 , 3 values counter, result should be

counter({4: 6, 5: 5, 6: 3, 1: 1, 7: 1}) 

here approaches:

filter(lambda x: x not in (2, 3), c) → [1, 4, 5, 6, 7] 

but don't want list.

c - set([ 2, 3 ]) → typeerror: unsupported operand type(s) -: 'counter' , 'set' 

i can use sth iterates on unpacked list of elements in counter this:

counter(x x in c.elements() if x not in (2, 3)) → counter({4: 6, 5: 5, 6: 3, 1: 1, 7: 1}) 

but unnecessarily costly large amounts.

the (not nice) solution found yet sth cumbersome this:

counter({ k: v k, v in c.iteritems() if k not in (2, 3) }) 

is there better, easier, more readable i'm overlooking?

why isn't there subtraction operator counter implemented can used set?

just use del:

>>> c = counter([ 1,2,3,4,5,6,7,6,5,4,3,2,3,4,5,6,5,4,3,4,5,4 ]) >>> c counter({4: 6, 5: 5, 3: 4, 6: 3, 2: 2, 1: 1, 7: 1}) >>> del c[2] >>> del c[3] >>> c counter({4: 6, 5: 5, 6: 3, 1: 1, 7: 1}) >>> 

just fun, substract counter large values keys remove, better stick del:

>>> c = counter([ 1,2,3,4,5,6,7,6,5,4,3,2,3,4,5,6,5,4,3,4,5,4 ]) >>> c counter({4: 6, 5: 5, 3: 4, 6: 3, 2: 2, 1: 1, 7: 1}) >>> c - counter({2:sys.maxint, 3:sys.maxint}) counter({4: 6, 5: 5, 6: 3, 1: 1, 7: 1}) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -