Like dict.update() but subtracts counts instead of replacing them. Counts can be reduced below zero. Both the inputs and outputs are allowed to contain zero and negative counts. Source can be an iterable, a dictionary, or another Counter instance. >>> c = Counter('
(self, iterable=None, /, **kwds)
| 706 | self.update(kwds) |
| 707 | |
| 708 | def subtract(self, iterable=None, /, **kwds): |
| 709 | '''Like dict.update() but subtracts counts instead of replacing them. |
| 710 | Counts can be reduced below zero. Both the inputs and outputs are |
| 711 | allowed to contain zero and negative counts. |
| 712 | |
| 713 | Source can be an iterable, a dictionary, or another Counter instance. |
| 714 | |
| 715 | >>> c = Counter('which') |
| 716 | >>> c.subtract('witch') # subtract elements from another iterable |
| 717 | >>> c.subtract(Counter('watch')) # subtract elements from another counter |
| 718 | >>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch |
| 719 | 0 |
| 720 | >>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch |
| 721 | -1 |
| 722 | |
| 723 | ''' |
| 724 | if iterable is not None: |
| 725 | self_get = self.get |
| 726 | if isinstance(iterable, _collections_abc.Mapping): |
| 727 | for elem, count in iterable.items(): |
| 728 | self[elem] = self_get(elem, 0) - count |
| 729 | else: |
| 730 | for elem in iterable: |
| 731 | self[elem] = self_get(elem, 0) - 1 |
| 732 | if kwds: |
| 733 | self.subtract(kwds) |
| 734 | |
| 735 | def copy(self): |
| 736 | 'Return a shallow copy.' |