collections中包含很多数据结构类,可以更方便地操作数据。
deque
Python 中可以用 deque 创建双端队列。
:::info 双端队列:同时具有栈和队列的特征,两端都可以增删元素,但不能在中间增删。 :::
from collections import dequedq = deque() # 创建一个空的双端队列dq = deque(序列) # 从已有序列创建双端队列dq.append('element') # 在队尾添加元素dq.appendleft('element') # 在队首添加元素ele = dq.pop() # 删除队尾元素并返回ele = dq.popleft() # 删除队首元素并返回
deque 在字节码级别就是线程安全的,所以常用来存储线程间共享的数据。
Counter
对序列元素计数,计数结果可以转化为字典或双值子序列。
from collections import Counterbreakfast = ['spam', 'spam', 'eggs', 'spam']breakfast_counter = Counter(breakfast)print(breakfast_counter) # output: Counter({'spam': 3, 'eggs': 1})print(breakfast_counter.most_common()) # output: [('spam', 3), ('eggs', 1)] 可以得到双值子序列print(breakfast_counter.most_common(1)) # output: [('spam', 3)] 可以得到出现次数最多的元素及其次数lunch = ['eggs', 'eggs', 'bacon']lunch_counter = Counter(lunch)print(dict(lunch_counter)) # output: {'eggs': 2, 'bacon': 1}print(breakfast_counter + lunch_counter) # 计数器可以相加,得到合并后的计数结果print(breakfast_counter - lunch_counter) # 计数器也可以相减
OrderedDict
由于字典是无序的,所以有些时候可能得不到想要的结果,因此 Python 提供了 OrderedDict 类用来创建有序字典。
from collections import OrderedDict# 与 dict() 相似,参数是一个双值子序列或一个字典或其他情况quotes = OrderedDict([('Moe', 'A wise guy, huh?'), ('Larry', 'Ow!'), ('Curly', 'Nyuk nyuk!')])
namedtuple
当想创建一个只有属性没有方法的类时,比如:
class Student:def __init__(self, id, name, age):self.id = idself.name = nameself.age = age
可以考虑用 namedtuple 代替:
from collections import namedtupleStudent = namedtuple('Student', 'id name age') # 创建 Student 类型st1 = Student(id=1, name='xiaoming', age=18) # 创建实例# 属性的调用方法与类相同st1.idst1.namest1.age
namedtuple 性能比类更好,但不能包含方法只能包含属性。
