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