python3 Counter模块

时间:2021-11-18 20:13:01
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