Python:如何乘以Counter对象的值?

8 投票
3 回答
6819 浏览
提问于 2025-04-18 06:39

我想找一种方法来对一个计数器对象里的值进行乘法运算,也就是:

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})

在Python中,通常怎么做这个呢?

我想这么做的原因是: 我有一个稀疏特征向量(用计数器对象表示的词袋),我想对它进行归一化处理。

3 个回答

0

你可以添加一个 Counter

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

这是一个老问题,但我在解析化学公式时遇到了同样的情况。我扩展了 Counter 类,使它可以和整数进行乘法运算。对我来说,下面的代码就足够了——如果需要的话,可以进一步扩展:

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))

通过上面的代码,你可以从左边和右边都用整数进行乘法。我需要重新定义 __add__ 方法,以确保类型 MCounter 不变。如果需要使用减法、&|,也需要类似地实现。

10

你可以这样做:

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

撰写回答