10.3 标准库
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])