python3 Counter模块

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(""))

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

执行结果:

4
None
1
None

 

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

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

执行结果:

''的数量:4
''的数量:1
''的数量:1
''的数量:1
''的数量:1
2

 

posted on 2019-04-29 16:57  lilyxiaoyy  阅读(2077)  评论(0编辑  收藏  举报

返回
顶部