Reputation: 715
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.
Upvotes: 8
Views: 7325
Reputation: 1914
This is an old question, but I just had the same issue during chemical formulae parsing. I extended the Counter
class to accept multiplication with integers. For my case, the following is sufficient - it may be extended on demand:
class MCounter(Counter):
"""This is a slight extention of the ``Collections.Counter`` class
to also allow multiplication with integers."""
def __mul__(self, other):
if not isinstance(other, int):
raise TypeError("Non-int factor")
return MCounter({k: other * v for k, v in self.items()})
def __rmul__(self, other):
return self * other # call __mul__
def __add__(self, other):
return MCounter(super().__add__(other))
So with above, you can multiply from left and right with integers as well. I needed to redefine __add__
such that the type MCounter
was preserved. If one needs to use subtraction, &
and |
, that needs to be implemented likewise.
Upvotes: 1
Reputation: 32189
You can add the Counter
:
b = a+a
>>> print b
Counter({'three': 6, 'two': 4, 'one': 2})
Upvotes: -1