Counter计数器,最主要的作用是计算“可迭代序列”中各个元素(element)的数量。具体用法如下:
使用前导入:
from collections import Counter
#对列表作用
list=[1,2,2,2,3,6,6,6,6]
print(Counter(list)) #Counter({6: 4, 2: 3, 1: 1, 3: 1})
#对字符串作用
temp=Counter('aabbcdeffgg')
print(temp) #Counter({'a': 2, 'b': 2, 'f': 2, 'g': 2, 'c': 1, 'd': 1, 'e': 1})
#对于其他可迭代序列也是同样的用法
Counter类型的数据
(1)转换为字典后输出
#查看数据类型
print(type(temp)) #
#转换为字典类型后输出
print(dict(temp)) #{'a': 2, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 2, 'g': 2}
for num,count in enumerate(dict(temp).items()):
print(count)
'''
('a', 2)
('b', 2)
('c', 1)
('d', 1)
('e', 1)
('f', 2)
('g', 2)
'''
(2)使用Counter自带的items()方法输出
print(temp.items()) #dict_items([('a', 2), ('b', 2), ('c', 1), ('d', 1), ('e', 1), ('f', 2), ('g', 2)])
for item in temp.items():
print(item)
'''
('a', 2)
('b', 2)
('c', 1)
('d', 1)
('e', 1)
('f', 2)
('g', 2)
'''
利用most_common()方法
from collections import Counter
c=Counter([1,2,2,2,3,6,6,6,6])
print(c.most_common(1)) #[(6, 4)] 统计出现次数最多的一个元素
print(c.most_common(2)) #[(6, 4), (2, 3)] 统计出现次数最多的两个元素
#没有指定个数,就列出全部
print(c.most_common()) #[(6, 4), (2, 3), (1, 1), (3, 1)]
from collections import Counter
c=Counter([1,-2,-2,-2,3,6,6,6,6])
print(c.elements())
''''''
print(list(c.elements()))
'''[1, -2, -2, -2, 3, 6, 6, 6, 6]'''
print(sorted(c.elements()))
'''列出所有元素(按大小排序
[-2, -2, -2, 1, 3, 6, 6, 6, 6]'''
print(sorted(c))
'''列出所有唯一元素(按大小排序)
[1, 2, 3, 6]'''
print(sorted(c,key=abs))
'''列出所有唯一元素(按绝对值大小排序)
[1, -2, 3, 6]'''
c.elements()中的元素可以直接迭代运算
from collections import Counter
c=Counter([1,-2,-2,-2,3,6,6,6,6])
sum=1
for i in c.elements():
sum*=i
print(sum)
'''-31104'''
from collections import Counter
c=Counter('ABCABCCC')
print(c.keys())
'''dict_keys(['A', 'B', 'C'])'''
print(c.values())
'''dict_values([2, 2, 4])'''
print(sum(c.values()))
'''8'''
from collections import Counter
c=Counter('ABCABCCC')
#查询具体某个元素的个数
print(c["A"]) #2
from collections import Counter
c=Counter('ABCABCCC')
#查询具体某个元素的个数
print(c.most_common())
'''[('C', 4), ('A', 2), ('B', 2)]'''
for elem in 'ADD':
'''新增了一个A,两个D'''
c[elem]+=1
print(c.most_common())
'''[('C', 4), ('A', 3), ('B', 2), ('D', 2)]'''
将元素全部删除
del c["C"]
'''将元素C全部删除'''
print(c.most_common())
'''[('A', 3), ('B', 2), ('D', 2)]'''
from collections import Counter
c=Counter('ABCABCCC')
d=Counter("CCDD")
c.update(d)
'''增加了两个C,两个D'''
c['C'] -= 2
'''减少两个C'''
print(c.most_common())
# [('D', 2), ('A', 2), ('B', 2), ('C', 0)]
# 本来上面,C有两个,现在只有零个了,被减少了。
Counter之间直接+或- ,可以减到0及0以下
print(Counter('AAB') + Counter('BCC'))
#Counter({'B': 2, 'C': 2, 'A': 2})
print(Counter("AAB")-Counter("BCC"))
#Counter({'A': 2})
可以减到0及0以下
s= Counter("AAB")
s.subtract("BCC")
print(subtract_test01)
'''Counter({'A': 2, 'B': 0, 'C': -2})'''
c.clear()
print(c) #Counter()
print(Counter('AAB') & Counter('BBCC'))
'''Counter({'B': 1})'''
print(Counter('AAB') | Counter('BBCC'))
'''Counter({'A': 2, 'C': 2, 'B': 2})'''