python计数器—collections.Counter

2022-07-13 09:35:49

Counter计数器,最主要的作用是计算“可迭代序列”中各个元素(element)的数量。具体用法如下:

使用前导入:

from collections import Counter

1.统计“可迭代序列”中每个元素出现的次数

对列表/字符串作用

#对列表作用
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))  #<class 'collections.Counter'>
#转换为字典类型后输出
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)
'''

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

3. 列出所有元素—elements()和sorted()

from collections import Counter
c=Counter([1,-2,-2,-2,3,6,6,6,6])

print(c.elements())
'''<itertools.chain object at 0x00000112C08E2E48>'''

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'''

4. 输出元素keys()和元素个数values()

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'''

5. 对具体元素的操作

(1)查询单元素个数

from collections import Counter
c=Counter('ABCABCCC')
#查询具体某个元素的个数
print(c["A"])  #2

(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)]'''

(3)删除元素del

将元素全部删除

del c["C"]
'''将元素C全部删除'''
print(c.most_common())
'''[('A', 3), ('B', 2), ('D', 2)]'''

(4)更新update()

from collections import Counter
c=Counter('ABCABCCC')
d=Counter("CCDD")
c.update(d)
'''增加了两个C,两个D'''

(5)增加与减少(+-)

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

(6) struct()减操作

可以减到0及0以下

s= Counter("AAB")
s.subtract("BCC")
print(subtract_test01)  
'''Counter({'A': 2, 'B': 0, 'C': -2})'''

 (7)清除clear

c.clear()
print(c)  #Counter()

(8)“与&"  "或|" 操作

print(Counter('AAB') & Counter('BBCC'))
'''Counter({'B': 1})'''

print(Counter('AAB') | Counter('BBCC'))
'''Counter({'A': 2, 'C': 2, 'B': 2})'''
  • 作者:Judy18
  • 原文链接:https://blog.csdn.net/Judy18/article/details/124048121
    更新时间:2022-07-13 09:35:49