from collections import Counter
基类继承自dict, 所有拥有若干的实例方法, 感觉就像是一种新的数据类型, 我想给她起个外号: 字典计数类型
传入的参数:
>>> 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
- 初始化一个counter,得到一个counter的实例化对象, counter类的基类为dict, 所以打印实例化对象会得到一个类似dict类型的class
from collections import Counter
c = Counter('abcdeabcdabcaba') # count elements from a string
b = Counter({'a': 4, 'b': 2})
a = Counter(a=4, b=2)
print(c)
print(b)
print(a)
# 结果
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
Counter({'a': 4, 'b': 2})
Counter({'a': 4, 'b': 2})
- 实例方法
from collections import Counter
c = Counter('abcdeabcdabcaba') # count elements from a string
b = Counter({'a': 4, 'b': 2})
a = Counter(a=4, b=2)
# print(c)
# print(b)
# print(a)
# Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
# Counter({'a': 4, 'b': 2})
# Counter({'a': 4, 'b': 2})
# d = c.most_common(3) # three most common elements 三个最常见的元素,如果参数为空, 则全部输出
#[('a', 5), ('b', 4), ('c', 3)]
# d = c.most_common()
#[('a', 5), ('b', 4), ('c', 3), ('d', 2), ('e', 1)]
# d = sorted(c) # list all unique elements 列出所有唯一的元素
#['a', 'b', 'c', 'd', 'e']
# d = sorted(c.elements()) #迭代器遍历元素,每个元素重复其count的次数
# ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
# d = ''.join(sorted(c.elements())) # list elements with repetitions 包含重复的列表元素
#'aaaaabbbbcccdde'
# d = sum(c.values()) # total of all counts 所有计数合计
#15
d = c['a'] # count of letter 'a' 计算元素a出现的次数
#5
for elem in 'shazam': # update counts from an iterable 更新可迭代对象的计数
c[elem] += 1 # by adding 1 to each element's count 通过给每个元素的计数加一
d = c['a'] # now there are seven 'a'
# 7
# 此时的c Counter({'a': 7, 'b': 4, 'c': 3, 'd': 2, 'e': 1, 's': 1, 'h': 1, 'z': 1, 'm': 1})
del c['b'] # remove all 'b' 删除元素b
d = c['b'] # now there are zero 'b'
#0
g = Counter('simsalabim') # make another counter 新建一个新的额counter
c.update(g) # add in the second counter 添加到另外一个counter
d = c['a'] # now there are nine 'a' 现在我们得到了9个元素a
# 9
# c.clear() # empty the counter 清空counter
d = 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
d = c.most_common() # 'b' is still in, but its count is zero 元素b仍然存在, 但是他的计数为0
# [('a', 3), ('c', 1), ('b', 0)]
print(d)