Tutorial by Examples

from collections import Counter c = Counter(["a", "b", "c", "d", "a", "b", "a", "c", "d"]) c # Out: Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2}) c["a"] # Out: 3 c[7] # not in the list (7 oc...
Counting the keys of a Mapping isn't possible with collections.Counter but we can count the values: from collections import Counter adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5} Counter(adict.values()) # Out: Counter({2: 2, 3: 1, 5: 3}) The most common elements are avaiable by the m...
alist = [1, 2, 3, 4, 1, 2, 1, 3, 4] alist.count(1) # Out: 3 atuple = ('bear', 'weasel', 'bear', 'frog') atuple.count('bear') # Out: 2 atuple.count('fox') # Out: 0
astring = 'thisisashorttext' astring.count('t') # Out: 4 This works even for substrings longer than one character: astring.count('th') # Out: 1 astring.count('is') # Out: 2 astring.count('text') # Out: 1 which would not be possible with collections.Counter which only counts single char...
To count the occurences of a value in a numpy array. This will work: >>> import numpy as np >>> a=np.array([0,3,4,3,5,4,7]) >>> print np.sum(a==3) 2 The logic is that the boolean statement produces a array where all occurences of the requested values are 1 and all o...

Page 1 of 1