Dict subclass for counting hashable items. Sometimes called a bag or multiset. Elements are stored as dictionary keys and their counts are stored as dictionary values. >>> c = Counter('abcdeabcdabcaba') # count elements from a string >>> c.most_common(3) # t
| 534 | pass |
| 535 | |
| 536 | class Counter(dict): |
| 537 | '''Dict subclass for counting hashable items. Sometimes called a bag |
| 538 | or multiset. Elements are stored as dictionary keys and their counts |
| 539 | are stored as dictionary values. |
| 540 | |
| 541 | >>> c = Counter('abcdeabcdabcaba') # count elements from a string |
| 542 | |
| 543 | >>> c.most_common(3) # three most common elements |
| 544 | [('a', 5), ('b', 4), ('c', 3)] |
| 545 | >>> sorted(c) # list all unique elements |
| 546 | ['a', 'b', 'c', 'd', 'e'] |
| 547 | >>> ''.join(sorted(c.elements())) # list elements with repetitions |
| 548 | 'aaaaabbbbcccdde' |
| 549 | >>> sum(c.values()) # total of all counts |
| 550 | 15 |
| 551 | |
| 552 | >>> c['a'] # count of letter 'a' |
| 553 | 5 |
| 554 | >>> for elem in 'shazam': # update counts from an iterable |
| 555 | ... c[elem] += 1 # by adding 1 to each element's count |
| 556 | >>> c['a'] # now there are seven 'a' |
| 557 | 7 |
| 558 | >>> del c['b'] # remove all 'b' |
| 559 | >>> c['b'] # now there are zero 'b' |
| 560 | 0 |
| 561 | |
| 562 | >>> d = Counter('simsalabim') # make another counter |
| 563 | >>> c.update(d) # add in the second counter |
| 564 | >>> c['a'] # now there are nine 'a' |
| 565 | 9 |
| 566 | |
| 567 | >>> c.clear() # empty the counter |
| 568 | >>> c |
| 569 | Counter() |
| 570 | |
| 571 | Note: If a count is set to zero or reduced to zero, it will remain |
| 572 | in the counter until the entry is deleted or the counter is cleared: |
| 573 | |
| 574 | >>> c = Counter('aaabbc') |
| 575 | >>> c['b'] -= 2 # reduce the count of 'b' by two |
| 576 | >>> c.most_common() # 'b' is still in, but its count is zero |
| 577 | [('a', 3), ('c', 1), ('b', 0)] |
| 578 | |
| 579 | ''' |
| 580 | # References: |
| 581 | # http://en.wikipedia.org/wiki/Multiset |
| 582 | # http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html |
| 583 | # http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm |
| 584 | # http://code.activestate.com/recipes/259174/ |
| 585 | # Knuth, TAOCP Vol. II section 4.6.3 |
| 586 | |
| 587 | def __init__(self, iterable=None, /, **kwds): |
| 588 | '''Create a new, empty Counter object. And if given, count elements |
| 589 | from an input iterable. Or, initialize the count from another mapping |
| 590 | of elements to their counts. |
| 591 | |
| 592 | >>> c = Counter() # a new, empty counter |
| 593 | >>> c = Counter('gallahad') # a new counter from an iterable |
no outgoing calls
no test coverage detected