【Python基础教程】第10章 模块
2015-02-09 22:56
267 查看
10.3 标准库
10.3.3 fileinput
![](http://img.blog.csdn.net/20150209225403930?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGFuaGFuMTIyNjU1OTA0/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
10.3.4 集合、堆和双端队列
1.集合set
Python中并没有独立的堆类型,只有一个包含堆操作的模块-heapq,包含6个函数,其中前四个直接和堆操作相关。
10.3.3 fileinput
#给脚本的每一行后面添加行号 import fileinput for line in fileinput.input(inplace = True): line = line.rstrip() num = fileinput.lineno() print '%-40s # %2i' % (line, num)
10.3.4 集合、堆和双端队列
1.集合set
>>> set(range(10)) set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> set([0, 1, 1, 1, 2, 3]) set([0, 1, 2, 3]) >>> #集合中元素的顺序是随意的 >>> set(['fee', 'fie', 'foe']) set(['foe', 'fee', 'fie']) >>> >>> #使用set进行标准集合操作(并,交,差等) >>> a = set([1, 2, 3]) >>> b = set([2, 3, 4]) >>> a.union(b) set([1, 2, 3, 4]) >>> a | b set([1, 2, 3, 4]) >>> c = a & b >>> c.issubset(a) True >>> c <= a True >>> c.issuperset(a) False >>> c >= a False >>> a.intersection(b) set([2, 3]) >>> a & b set([2, 3]) >>> a.difference(b) set([1]) >>> a.symmetric_difference(b) set([1, 4]) >>> a ^ b set([1, 4]) >>> a.copy() set([1, 2, 3]) >>> a.copy() is a False >>> >>> #集合是可变的,但集合本身只能包含不可表的值,所以不能包含其他集合。 >>> #如何使用集合的集合那?方法:frozenset-不可变集合 >>> a = set() >>> b = set() >>> a.add(b) Traceback (most recent call last): File "<pyshell#27>", line 1, in <module> a.add(b) TypeError: unhashable type: 'set' >>> a.add(frozenset(b))2.堆
Python中并没有独立的堆类型,只有一个包含堆操作的模块-heapq,包含6个函数,其中前四个直接和堆操作相关。
>>> #使用heappush建立堆 >>> from heapq import * >>> from random import shuffle >>> data = range(10) >>> shuffle(data) >>> heap = [] >>> for n in data: heappush(heap, n) >>> heap [0, 1, 2, 3, 4, 5, 8, 7, 6, 9] >>> heappush(heap, 0.5) >>> heap [0, 0.5, 2, 3, 1, 5, 8, 7, 6, 9, 4] >>> heappop(heap) 0 >>> heap [0.5, 1, 2, 3, 4, 5, 8, 7, 6, 9] >>> #如果没有使用heappush建立堆,在使用heappush和heappop前应该使用heapify,将列表变为堆 >>> heap = [5, 8, 0, 3, 6, 7, 9, 1, 4, 2] >>> heapify(heap) >>> heap [0, 1, 5, 3, 2, 7, 9, 8, 4, 6] >>> heapreplace(heap, 0.5) 0 >>> heap [0.5, 1, 5, 3, 2, 7, 9, 8, 4, 6]3.双端队列
>>> from collections import deque >>> q = deque(range(5)) >>> q.append(5) >>> q.appendleft(6) >>> q deque([6, 0, 1, 2, 3, 4, 5]) >>> q.pop() 5 >>> q.popleft() 6 >>> q deque([0, 1, 2, 3, 4]) >>> q.rotate(3) >>> q deque([2, 3, 4, 0, 1]) >>> q.rotate(-1) >>> q deque([3, 4, 0, 1, 2])
相关文章推荐
- Python基础教程 第10章: 自带电池(模块) 学习笔记
- python基础教程_学习笔记12:充电时刻——模块
- Python基础教程之函数与模块
- <<Python基础教程>>学习笔记 | 第10章 | 充电时刻
- python基础教程共60课-第38课模块
- Python安装使用命令行交互模块pexpect的基础教程
- python基础教程之数字处理(math)模块详解
- <<Python基础教程>>学习笔记 | 第10章 | 充电时刻
- python基础教程_学习笔记12:充电时刻——模块
- Python安装使用命令行交互模块pexpect的基础教程
- Python基础教程之正则表达式基本语法以及re模块
- Python基础教程(七):函数、模块
- python基础教程之数字处理(math)模块详解
- CDays–2 完成核心功能 CMD模块 Python基础教程 cmd cli
- 【C012】Python - 基础教程学习(三)
- Python基础:函数、类、模块
- Python - 基础教程学习(第三章 & 第四章)
- xml-RPC Python基础教程
- Python基础(5):模块
- 一些关于面向对象的思考(摘自python基础教程)