前言
之前認識了python基本的數據類型和數據結構,現在認識一個高級的:Collections,一個模塊主要用來干嘛,有哪些類可以使用,看__init__.py就知道
'''This module implements specialized container datatypes providing
alternatives to Python's general purpose built-in containers, dict,
list, set, and tuple.* namedtuple factory function for creating tuple subclasses with named fields
* deque list-like container with fast appends and pops on either end
* ChainMap dict-like class for creating a single view of multiple mappings
* Counter dict subclass for counting hashable objects
* OrderedDict dict subclass that remembers the order entries were added
* defaultdict dict subclass that calls a factory function to supply missing values
* UserDict wrapper around dictionary objects for easier dict subclassing
* UserList wrapper around list objects for easier list subclassing
* UserString wrapper around string objects for easier string subclassing'''
__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
'UserString', 'Counter', 'OrderedDict', 'ChainMap']
collections模塊實現一些特定的數據類型,可以替代Python中常用的內置數據類型如dict, list, set, tuple,簡單說就是對基本數據類型做了更上一層的處理。
一、deque
用途:雙端隊列,頭部和尾部都能以O(1)時間復雜度插入和刪除元素。類似于列表的容器
所謂雙端隊列,就是兩端都能操作,與Python內置的list區別在于:頭部插入與刪除的時間復雜度為O(1),來個栗子感受一下:
#!/usr/bin/env python# -*- coding:utf-8 -*-# __author__ = 'liao gao xiang'"""保留最后n個元素"""from collections import dequedef search(file, pattern, history=5): previous_lines = deque(maxlen=history) for l in file: if pattern in l: yield l, previous_lines # 使用yield表達式的生成器函數,將搜索過程的代碼和搜索結果的代碼解耦 previous_lines.append(l)with open(b'file.txt', mode='r', encoding='utf-8') as f: for line, prevlines in search(f, 'Python', 5): for pline in prevlines: print(pline, end='') print(line, end='')d = deque()d.append(1)d.append("2")print(len(d))print(d[0], d[1])d.extendleft([0])print(d)d.extend([6, 7, 8])print(d)d2 = deque('12345')print(len(d2))d2.popleft()print(d2)d2.pop()print(d2)# 在隊列兩端插入或刪除元素時間復雜度都是 O(1) ,區別于列表,在列表的開頭插入或刪除元素的時間復雜度為 O(N)d3 = deque(maxlen=2)d3.append(1)d3.append(2)print(d3)d3.append(3)print(d3)
新聞熱點
疑難解答