首页 > 编程 > Python > 正文

Python中collections模块的基本使用教程

2020-02-15 23:59:33
字体:
来源:转载
供稿:网友

前言

之前认识了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)            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表