# HG changeset patch # User Lars Buitinck # Date 1317977368 -7200 # Node ID f023dcafaf3b96ca4c2d1ab0c55ea1ae71dc0e34 # Parent 9c1b76936b7941c745ef157777e833106cb5b7ac Added __iadd__ to collections.Counter for faster += Changes behavior: after from collections import Counter a = Counter([1,2,3]) b = a a += Counter([3,4,5]) it used to be that (a is not b), but now (a is b). diff -r 9c1b76936b79 -r f023dcafaf3b Lib/collections/__init__.py --- a/Lib/collections/__init__.py Fri Oct 07 10:01:28 2011 +0200 +++ b/Lib/collections/__init__.py Fri Oct 07 10:49:28 2011 +0200 @@ -604,17 +604,27 @@ Counter({'b': 4, 'c': 2, 'a': 1}) ''' + result = Counter() + result += self + result += other + return result + + def __iadd__(self, other): + '''Add counts from other counter. + + Like update, but only adds Counters and takes no keyword arguments. + + >>> c = Counter('abbb') + >>> c += Counter('bcc') + Counter({'b': 4, 'c': 2, 'a': 1}) + + ''' if not isinstance(other, Counter): return NotImplemented - result = Counter() - for elem, count in self.items(): - newcount = count + other[elem] - if newcount > 0: - result[elem] = newcount for elem, count in other.items(): - if elem not in self and count > 0: - result[elem] = count - return result + if count > 0: + self[elem] += count + return self def __sub__(self, other): ''' Subtract count, but keep only results with positive counts.