Python collections模块之Counter()详解

简介: Python collections模块之Counter()详解

Python collections模块之Counter详解

前言

from collections import Counter
Counter()
most_common()
elements()
update()
subtract()
collections模块 ==> Python标准库,数据结构常用的模块;collections包含了一些特殊的容器,针对Python内置的容器,例如list、dict、set和tuple,提供了另一种选择。

collections模块常用类型有:


1.计数器(Counter)

dict的子类,计算可hash的对象

2.双向队列(deque)

类似于list的容器,可以快速的在队列头部和尾部添加、删除元素

3.默认字典(defaultdict)

dict的子类,可以调用提供默认值的函数

4.有序字典(OrderedDict)

dict的子类,可以记住元素的添加顺序

可命名元组(namedtuple)

可以创建包含名称的tuple

Counter()

主要功能:可以支持方便、快速的计数,将元素数量统计,然后计数并返回一个字典,键为元素,值为元素个数。

from collections import Counter

list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"]
dic = Counter(list1)
print(dic)
#结果:次数是从高到低的
#Counter({'a': 3, 'g': 3, 'c': 2, 'f': 2, 'b': 1})

print(dict(dic))
#结果:按字母顺序排序的
#{'a': 3, 'b': 1, 'c': 2, 'f': 2, 'g': 3}

print(dic.items()) #dic.items()获取字典的key和value
#结果:按字母顺序排序的
#dict_items([('a', 3), ('b', 1), ('c', 2), ('f', 2), ('g', 3)])

print(dic.keys())
#结果:
#dict_keys(['a', 'b', 'c', 'f', 'g'])

print(dic.values())
#结果:
#dict_values([3, 1, 2, 2, 3])

print(sorted(dic.items(), key=lambda s: (-s[1])))
#结果:按统计次数降序排序
#[('a', 3), ('g', 3), ('c', 2), ('f', 2), ('b', 1)]

for i, v in dic.items():
    if v == 1:
        print(i)
#结果:
#b
from collections import Counter
str1 = "aabbfkrigbgsejaae"
print(Counter(str1))
print(dict(Counter(str1)))
#结果:
#Counter({'a': 4, 'b': 3, 'g': 2, 'e': 2, 'f': 1, 'k': 1, 'r': 1, 'i': 1, 's': 1, 'j': 1})
#{'a': 4, 'b': 3, 'f': 1, 'k': 1, 'r': 1, 'i': 1, 'g': 2, 's': 1, 'e': 2, 'j': 1}
dic1 = {'a': 3, 'b': 4, 'c': 0, 'd': -2}
print(Counter(dic1))

Counter对象支持以下三个字典不支持的方法,update()字典支持

most_common()

返回一个列表,包含counter中n个最大数目的元素,如果忽略n或者为None,most_common()将会返回counter中的所有元素,元素有着相同数目的将会选择出现早的元素

list1 = ["a", "a", "a", "b", "c", "f", "g", "g", "c", "11", "g", "f", "10", "2"]
print(Counter(list1).most_common(3))
#结果:[('a', 3), ('g', 3), ('c', 2)]

#"c""f"调换位置,结果变化
list2 = ["a", "a", "a", "b", "f", "c", "g", "g", "c", "11", "g", "f", "10", "2"]
print(Counter(list2).most_common(3))
#结果:[('a', 3), ('g', 3), ('f', 2)]
#Counter({'S': 916, 'C': 270, 'Q': 123})
fillc=count.most_common(1)[0][0]  #返回一个元素,第1行第一个
fillc
'S'

elements()

返回一个迭代器,每个元素重复的次数为它的数目,顺序是任意的顺序,如果一个元素的数目少于1,那么elements()就会忽略它

list2 = ["a", "a", "abdz", "abc", "f", "c", "g", "g", "c", "c1a1", "g", "f", "111000", "b10"]
print(''.join(Counter(list2).elements()))
#结果:aaabdzabcffccgggc1a1111000b10
print(''.join(list2))
#结果:aaabdzabcfcggcc1a1gf111000b10
dic1 = {'a': 3, 'b': 4, 'c': 0, 'd': -2, "e": 0}
print(Counter(dic1))
print(list(Counter(dic1).elements()))
#结果:
#Counter({'b': 4, 'a': 3, 'c': 0, 'e': 0, 'd': -2})
#['a', 'a', 'a', 'b', 'b', 'b', 'b']

update()

从一个可迭代对象(可迭代对象是一个元素序列,而非(key,value)对构成的序列)中或者另一个映射(或counter)中所有元素相加,是数目相加而非替换它们

dic1 = {'a': 3, 'b': 4, 'c': 0, 'd': -2, "e": 0}
dic2 = {'a': 3, 'b': 4, 'c': 0, 'd': 2, "e": -1, "f": 6}
a = Counter(dic1)
print(a)
#结果:Counter({'b': 4, 'a': 3, 'c': 0, 'e': 0, 'd': -2})
b = Counter(dic2)
print(b)
#结果:Counter({'f': 6, 'b': 4, 'a': 3, 'd': 2, 'c': 0, 'e': -1})

a.update(b)
print(a)
#结果:Counter({'b': 8, 'a': 6, 'f': 6, 'c': 0, 'd': 0, 'e': -1})

ubtract()

从一个可迭代对象中或者另一个映射(或counter)中,元素相减,是数目相减而不是替换它们

dic1 = {'a': 3, 'b': 4, 'c': 0, 'd': -2, "e": 0}
dic2 = {'a': 3, 'b': 4, 'c': 0, 'd': 2, "e": -1, "f": 6}
a = Counter(dic1)
print(a)
#结果:Counter({'b': 4, 'a': 3, 'c': 0, 'e': 0, 'd': -2})
b = Counter(dic2)
print(b)
#结果:Counter({'f': 6, 'b': 4, 'a': 3, 'd': 2, 'c': 0, 'e': -1})
a.subtract(b)
print(a)
#结果:Counter({'e': 1, 'a': 0, 'b': 0, 'c': 0, 'd': -4, 'f': -6})
相关文章
|
2天前
|
API Python
python ratelimit模块
python ratelimit模块
|
2天前
|
Python
像导入Python模块一样导入ipynb文件
像导入Python模块一样导入ipynb文件
|
2天前
|
算法 Python
python tarfile模块
python tarfile模块
|
2天前
|
Python
如何在 Python 中导入模块
【8月更文挑战第29天】
13 1
|
2天前
|
Python
|
2天前
|
数据采集 JSON 算法框架/工具
我常用的几个经典Python模块
我常用的几个经典Python模块
|
2天前
|
开发者 Python
什么是 python 模块?
【8月更文挑战第29天】
4 0
|
4月前
|
存储 开发者 Python
Python中的collections模块与UserDict:用户自定义字典详解
【4月更文挑战第2天】在Python中,`collections.UserDict`是用于创建自定义字典行为的基类,它提供了一个可扩展的接口。通过继承`UserDict`,可以轻松添加或修改字典功能,如在`__init__`和`__setitem__`等方法中插入自定义逻辑。使用`UserDict`有助于保持代码可读性和可维护性,而不是直接继承内置的`dict`。例如,可以创建一个`LoggingDict`类,在设置键值对时记录操作。这样,开发者可以根据具体需求定制字典行为,同时保持对字典内部管理的抽象。
|
4月前
|
存储 缓存 算法
Python中collections模块的deque双端队列:深入解析与应用
在Python的`collections`模块中,`deque`(双端队列)是一个线程安全、快速添加和删除元素的双端队列数据类型。它支持从队列的两端添加和弹出元素,提供了比列表更高的效率,特别是在处理大型数据集时。本文将详细解析`deque`的原理、使用方法以及它在各种场景中的应用。
|
2天前
|
存储 Python 容器
python内置collections模块的使用
python内置collections模块的使用
6 0
下一篇
云函数