python3 Counter模块

时间:2019-04-29 17:26:00   收藏:0   阅读:153
from collections import Counter

c = Counter("周周周周都方法及")
print(c)
print(type(c))
print(‘__iter__‘ in dir(c))
print(‘__next__‘ in dir(c))
print(‘items‘ in dir(c))

执行结果:
Counter({‘周‘: 4, ‘方‘: 1, ‘及‘: 1, ‘都‘: 1, ‘法‘: 1})
<class ‘collections.Counter‘>
True
False
True

‘‘‘get()方法获取元素出现的次数,没找到,则为None‘‘‘
print(c.get("周"))
print(c.get("好"))

执行结果:
4
None

for k, v in c.items():
print("‘"+k+"‘的数量:"+str(v))

执行结果:
‘方‘的数量:1
‘及‘的数量:1
‘都‘的数量:1
‘法‘的数量:1
‘周‘的数量:4

‘‘‘和字典get()方法一样‘‘‘
dic = {"a": 1, "b": 2, "c": 3}
print(dic.get(‘a‘))
print(dic.get(‘g‘))

执行结果:
1
None

‘‘‘统计列表列表中"周杰伦‘出现的次数‘‘‘
lst = ["赵本山", "河正宇", "黄海", "追击者", "周杰伦", "周杰伦"]
c = Counter(lst)
print(c.get("周杰伦"))

执行结果:
2

 

原文:https://www.cnblogs.com/lilyxiaoyy/p/10791452.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!