Python中的计数器 |设置 2(访问计数器)
Python中的计数器 |设置 1(初始化和更新)
一旦初始化,就可以像访问字典一样访问计数器。此外,它不会引发 KeyValue 错误(如果键不存在),而是值的计数显示为 0。
例子 :
# Python program to demonstrate accessing of
# Counter elements
from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
print(col_count)
col = ['blue','red','yellow','green']
# Here green is not in col_count
# so count of green will be zero
for color in col:
print (color, col_count[color])
输出:
Counter({'blue': 3, 'red': 2, 'yellow': 1})
blue 3
red 2
yellow 1
green 0
元素():
elements() 方法返回一个迭代器,该迭代器生成 Counter 已知的所有项目。
注意:不包括 count <= 0 的元素。
例子 :
# Python example to demonstrate elements() on
# Counter (gives back list)
from collections import Counter
coun = Counter(a=1, b=2, c=3)
print(coun)
print(list(coun.elements()))
输出 :
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']
最常见的() :
most_common() 用于生成 n 个最常遇到的输入值及其各自计数的序列。
# Python example to demonstrate most_elements() on
# Counter
from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
print('%s: %d' % (letter, count))
输出 :
f: 219
d: 120
c: 3