Python计数器collections.Counter

参考:
https://docs.python.org/zh-cn/3/library/collections.html#collections.Counter
https://blog.csdn.net/sinat_28576553/article/details/99131954 强烈推荐
https://blog.csdn.net/qq_39478403/article/details/105318754

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

#首先引入该方法
from collections import Counter

#对列表作用
list_01 = [1,9,9,5,0,8,0,9]  #GNZ48-陈珂生日
print(Counter(list_01))  #Counter({9: 3, 0: 2, 1: 1, 5: 1, 8: 1})
 
#对字符串作用
temp = Counter('abcdeabcdabcaba')
print(temp)  #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
#以上其实是两种使用方法,一种是直接用,一种是实例化以后使用,如果要频繁调用的话,显然后一种更简洁

print(temp.items()) #dict_items([('e', 1), ('c', 3), ('b', 4), ('d', 2), ('a', 5)])
 
for item in temp.items():
    print(item)
"""
('a', 5)
('c', 3)
('d', 2)
('e', 1)
('b', 4)
"""

算术与集合运算

>>> h1 = Counter(x=1, y=2)
>>> h2 = Counter(x=2, y=1)
>>> h3 = Counter(x=1, y=-1)
 
>>> h1 + h2
Counter({'x': 3, 'y': 3})  # 按元素相加
>>> h2 + h3
Counter({'x': 3})  # value <= 0 的会被删除
 
>>> h1 - h2
Counter({'y': 1})  # 按元素相减
>>> h1 - h3
Counter({'y': 3})  # value <= 0 的会被删除
 
>>> h1 & h2
Counter({'x': 1, 'y': 1})  # 按元素取 min() (交集)
 
>>> h1 | h2
Counter({'x': 2, 'y': 2})  # 按元素取 max() (并集)
posted @ 2022-04-05 12:43  麦克斯的园丁  阅读(53)  评论(0编辑  收藏  举报