diff options
author | Raymond Hettinger <python@rcn.com> | 2010-12-15 16:30:37 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2010-12-15 16:30:37 (GMT) |
commit | 96f3410ebeaf970d7f214d1be1527d8e7c1cc03b (patch) | |
tree | 329232dc4455df1d39c026d649f95a49fd17361f /Lib/collections.py | |
parent | 779f19e7a7116da0a683498260077eec1a40257a (diff) | |
download | cpython-96f3410ebeaf970d7f214d1be1527d8e7c1cc03b.zip cpython-96f3410ebeaf970d7f214d1be1527d8e7c1cc03b.tar.gz cpython-96f3410ebeaf970d7f214d1be1527d8e7c1cc03b.tar.bz2 |
Issue 10667: Fast path for collections.Counter
Diffstat (limited to 'Lib/collections.py')
-rw-r--r-- | Lib/collections.py | 15 |
1 files changed, 12 insertions, 3 deletions
diff --git a/Lib/collections.py b/Lib/collections.py index f05d7b4..061106b 100644 --- a/Lib/collections.py +++ b/Lib/collections.py @@ -334,6 +334,17 @@ def namedtuple(typename, field_names, verbose=False, rename=False): ### Counter ######################################################################## +def _count_elements(mapping, iterable): + 'Tally elements from the iterable.' + mapping_get = mapping.get + for elem in iterable: + mapping[elem] = mapping_get(elem, 0) + 1 + +try: # Load C helper function if available + from _collections import _count_elements +except ImportError: + pass + class Counter(dict): '''Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts @@ -476,9 +487,7 @@ class Counter(dict): else: dict.update(self, iterable) # fast path when counter is empty else: - self_get = self.get - for elem in iterable: - self[elem] = 1 + self_get(elem, 0) + _count_elements(self, iterable) if kwds: self.update(kwds) |