从多个计数器中取最大值而不是将它们相加 - Python

Taking the max from multiple Counters instead of adding them up - Python

如何才能 "combine" 多个 Counter 但只为 "combined" 计数器的每个键取最大值?

给定几个这样的计数器:

>>> from collections import Counter
>>> x = Counter([('a'), ('a', 'bc'), ('a', 'bc'), ('xyz', 'hooli')])
>>> y = Counter([('a'), ('a'), ('a'), ('asd', 'asd')])

我可以这样做来把它们加起来:

>>> x + y
Counter({'a': 4, ('a', 'bc'): 2, ('asd', 'asd'): 1, ('xyz', 'hooli'): 1})

但是,如果我的目标是合并计数器,但如果它们具有相同的密钥,则目标是不增加值,而是取值它的最大值我该怎么做?

我试过以下代码:

>>> z = Counter()
>>> for c in [x,y]:
...     for k in c:
...             z[k] = max(z.get(k,0), c[k])
... 
>>> z
Counter({'a': 3, ('a', 'bc'): 2, ('asd', 'asd'): 1, ('xyz', 'hooli'): 1})

但是有没有其他方法可以实现相同的输出?

Counter联合运算符(|)returns最大计数:

>>> x | y
Counter({'a': 3, ('a', 'bc'): 2, ('xyz', 'hooli'): 1, ('asd', 'asd'): 1})