Python Cookbook - 1 - 数据结构和算法
1 序列解压:通过*来通配
*a, b = somelist, first, *mid, last = somelist, a, *b = somelist
2 使用双向队列: from collections import deque
q = deque(maxlen=5) 可以固定长度
q = deque() 也可以任意长度
可以从两端进行插入和删除,append, appendleft, pop , popleft
3 查找最大或最小的N个元素: 使用heapq (堆队列)
heapq.nlargest(N, alist) heapq.nsmallest(N, alist) 适合N相对较小时
也可以sorted(alist)[-N:] sorted(alist)[:N] 适合N相对较大时
4 实现一个优先级队列
import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): heapq.heappush(self._queue, (-priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1]
5 字段中的键映射多个值 defaultdict
from collections import defaultdict
d = defaultdict(list)
d['a'].append(1)
d['a'].append(2)
d['b'].append(5)
KEEP LEARNING!