tlpipe.timestream.detect_ns.Counter¶
-
class
tlpipe.timestream.detect_ns.
Counter
(iterable=None, **kwds)[source]¶ 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 most common elements [('a', 5), ('b', 4), ('c', 3)] >>> sorted(c) # list all unique elements ['a', 'b', 'c', 'd', 'e'] >>> ''.join(sorted(c.elements())) # list elements with repetitions 'aaaaabbbbcccdde' >>> sum(c.values()) # total of all counts 15
>>> c['a'] # count of letter 'a' 5 >>> for elem in 'shazam': # update counts from an iterable ... c[elem] += 1 # by adding 1 to each element's count >>> c['a'] # now there are seven 'a' 7 >>> del c['b'] # remove all 'b' >>> c['b'] # now there are zero 'b' 0
>>> d = Counter('simsalabim') # make another counter >>> c.update(d) # add in the second counter >>> c['a'] # now there are nine 'a' 9
>>> c.clear() # empty the counter >>> c Counter()
Note: If a count is set to zero or reduced to zero, it will remain in the counter until the entry is deleted or the counter is cleared:
>>> c = Counter('aaabbc') >>> c['b'] -= 2 # reduce the count of 'b' by two >>> c.most_common() # 'b' is still in, but its count is zero [('a', 3), ('c', 1), ('b', 0)]
-
__init__
(iterable=None, **kwds)[source]¶ Create a new, empty Counter object. And if given, count elements from an input iterable. Or, initialize the count from another mapping of elements to their counts.
>>> c = Counter() # a new, empty counter >>> c = Counter('gallahad') # a new counter from an iterable >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping >>> c = Counter(a=4, b=2) # a new counter from keyword args
Methods
clear
(() -> None. Remove all items from D.)copy
()Return a shallow copy. elements
()Iterator over elements repeating each as many times as its count. fromkeys
(iterable[, v])get
((k[,d]) -> D[k] if k in D, ...)has_key
((k) -> True if D has a key k, else False)items
(() -> list of D’s (key, value) pairs, ...)iteritems
(() -> an iterator over the (key, ...)iterkeys
(() -> an iterator over the keys of D)itervalues
(...)keys
(() -> list of D’s keys)most_common
([n])List the n most common elements and their counts from the most common to the least. pop
((k[,d]) -> v, ...)If key is not found, d is returned if given, otherwise KeyError is raised popitem
(() -> (k, v), ...)2-tuple; but raise KeyError if D is empty. setdefault
((k[,d]) -> D.get(k,d), ...)subtract
([iterable])Like dict.update() but subtracts counts instead of replacing them. update
([iterable])Like dict.update() but add counts instead of replacing them. values
(() -> list of D’s values)viewitems
(...)viewkeys
(...)viewvalues
(...)-