Taking maximum from multiple counters instead of adding them - Python

How else to "combine" several Counter, but only assuming the maximum value for each key for the "combined" counter?

Given a couple of counters per se:

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

I could do this to add them:

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

But if my goal is to get a combination of counters, but if they have the same key, the goal is NOT to add values ​​up, but instead take max This. How to do it?

I tried the following code:

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

But is there any other way to achieve the same solution?

+4
source share
1 answer

Counter (|) :

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

Source: https://habr.com/ru/post/1622461/


All Articles