]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-25478: Add total() method to collections.Counter (GH-25829)
authorRaymond Hettinger <rhettinger@users.noreply.github.com>
Mon, 3 May 2021 03:19:51 +0000 (20:19 -0700)
committerGitHub <noreply@github.com>
Mon, 3 May 2021 03:19:51 +0000 (20:19 -0700)
Doc/library/collections.rst
Lib/collections/__init__.py
Lib/test/test_collections.py
Misc/NEWS.d/next/Library/2021-05-02-19-17-20.bpo-25478.AwlwdA.rst [new file with mode: 0644]

index 723c9da7be8d7bab1f68187d47993944e1d05cfa..94166ec6c754a78decd9718cbedd43b09f6aee30 100644 (file)
@@ -313,6 +313,16 @@ For example::
 
         .. versionadded:: 3.2
 
+    .. method:: total()
+
+        Compute the sum of the counts.
+
+            >>> c = Counter(a=10, b=5, c=0)
+            >>> c.total()
+            15
+
+        .. versionadded:: 3.10
+
     The usual dictionary methods are available for :class:`Counter` objects
     except for two which work differently for counters.
 
@@ -342,7 +352,7 @@ All of those tests treat missing elements as having zero counts so that
 
 Common patterns for working with :class:`Counter` objects::
 
-    sum(c.values())                 # total of all counts
+    c.total()                       # total of all counts
     c.clear()                       # reset all counts
     list(c)                         # list unique elements
     set(c)                          # convert to a set
index 89c73bbf2c10d9b99e1fe9460bde3add8a94bb12..bae0805d6686c5267cad435fac99f08b78bea7bf 100644 (file)
@@ -581,6 +581,10 @@ class Counter(dict):
         # Needed so that self[missing_item] does not raise KeyError
         return 0
 
+    def total(self):
+        'Sum of the counts'
+        return sum(self.values())
+
     def most_common(self, n=None):
         '''List the n most common elements and their counts from the most
         common to the least.  If n is None, then list all element counts.
index 2ba1a19ead9d8379fccc10739402e006ad449f05..f98048b34a7a1d705e953d05a4930dc5691e73ee 100644 (file)
@@ -2066,6 +2066,10 @@ class TestCounter(unittest.TestCase):
         self.assertRaises(TypeError, Counter, (), ())
         self.assertRaises(TypeError, Counter.__init__)
 
+    def test_total(self):
+        c = Counter(a=10, b=5, c=0)
+        self.assertEqual(c.total(), 15)
+
     def test_order_preservation(self):
         # Input order dictates items() order
         self.assertEqual(list(Counter('abracadabra').items()),
diff --git a/Misc/NEWS.d/next/Library/2021-05-02-19-17-20.bpo-25478.AwlwdA.rst b/Misc/NEWS.d/next/Library/2021-05-02-19-17-20.bpo-25478.AwlwdA.rst
new file mode 100644 (file)
index 0000000..81d2724
--- /dev/null
@@ -0,0 +1,2 @@
+Added a *total()* method to collections.Counter() to compute the sum of the
+counts.