Python中的计数器|集2(访问计数器)

Python中的计数器|集1(初始化和更新)

null

一旦初始化,计数器就像字典一样被访问。此外,它不会引发KeyValue错误(如果key不存在),而是将值的计数显示为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

元素(): 方法返回一个迭代器,该迭代器生成计数器已知的所有项。 注:不包括计数小于等于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

本文由 马扬克·拉瓦特 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享