5

Python 收集计数器 好奇是否有更好的方法来做到这一点。覆盖 Counter 类方法?内置乘法产生两个计数器的点积

from collections import Counter
a = Counter({'b': 4, 'c': 2, 'a': 1})
b = Counter({'b': 8, 'c': 4, 'a': 2})    
newcounter = Counter()
for x in a.elements():
    for y in b.elements():
        if x == y:
             newcounter[x] = a[x]*b[y]

$ newcounter
Counter({'b': 32, 'c': 8, 'a': 2})
4

3 回答 3

6

假设a并且b始终具有相同的键,您可以通过字典理解来实现这一点,如下所示:

a = Counter({'b': 4, 'c': 2, 'a': 1})
b = Counter({'b': 8, 'c': 4, 'a': 2})
c = Counter({k:a[k]*b[k] for k in a})
print(c)

输出

Counter({'b': 32, 'c': 8, 'a': 2})
于 2016-03-01T10:49:27.820 回答
3

如果您没有相同的字典,您可以获得键的交集:

from collections import Counter

a = Counter({'b': 4, 'c': 2, 'a': 1, "d":4})
b = Counter({'b': 8, 'c': 4, 'a': 2})

# just .keys() for python3
print Counter(({k: a[k] * b[k] for k in a.viewkeys() & b}))
Counter({'b': 32, 'c': 8, 'a': 2})

或者,如果您想同时加入,也可以加入dicts并使用 dict.get:

from collections import Counter

a = Counter({'b': 4, 'c': 2, 'a': 1, "d":4})
b = Counter({'b': 8, 'c': 4, 'a': 2})


print Counter({k: a.get(k,1) * b.get(k, 1) for k in a.viewkeys() | b})
Counter({'b': 32, 'c': 8, 'd': 4, 'a': 2})

如果您希望能够在 Counter dicts 上使用 * 运算符,则必须自己动手:

class _Counter(Counter):
    def __mul__(self, other):
        return _Counter({k: self[k] * other[k] for k in self.viewkeys() & other})

a = _Counter({'b': 4, 'c': 2, 'a': 1, "d": 4})
b = _Counter({'b': 8, 'c': 4, 'a': 2})

print(a * b)

这会给你:

_Counter({'b': 32, 'c': 8, 'a': 2})

如果你想就地:

from collections import Counter


class _Counter(Counter):
    def __imul__(self, other):
        return _Counter({k: self[k] * other[k] for k in self.viewkeys() & other})

输出:

In [28]: a = _Counter({'b': 4, 'c': 2, 'a': 1, "d": 4})

In [29]: b = _Counter({'b': 8, 'c': 4, 'a': 2})

In [30]: a *= b

In [31]: a
Out[31]: _Counter({'a': 2, 'b': 32, 'c': 8})
于 2016-03-01T10:54:21.847 回答
1

这似乎好一点:

a = Counter({'b': 4, 'c': 2, 'a': 1})
b = Counter({'b': 8, 'c': 4, 'a': 2})    

newcounter = Counter({k:a[k]*v for k,v in b.items()})

>>> newcounter
Counter({'b': 32, 'c': 8, 'a': 2})
于 2016-03-01T10:56:05.393 回答