Search code examples
pythoncountermultiplication

Python: How to multiply values of a Counter object?


I'm looking for a way to multiply the values of a Counter object, i.e.

a =  collections.Counter(one=1, two=2, three=3)
>>> Counter({'three': 3, 'two': 2, 'one': 1})

b = a*2
>>> Counter({'three': 6, 'two': 4, 'one': 2})

What's the standard way of doing this in python?

Why I want to do this: I have a sparse feature vector (bag of words represented by a Counter object) that I would like to normalize.


Solution

  • You can do this :

    for k in a.keys():
         a[k] = a[k] * 2