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})

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

你可能感兴趣的:(python3 Counter模块)