1 Sequence decompression: through * to pass the match
*a, B = somelist, First, *mid, last = Somelist, a, *b = Somelist
2 using bidirectional queues: From collections import deque
Q = deque (maxlen=5) can be fixed length
Q = deque () can also be any length
can be inserted and removed from both ends, append, Appendleft, pop, popleft
3 finding the largest or smallest n elements: using heapq (heap queue)
HEAPQ. nlargest (N, Alist) heapq. nsmallest (n, alist) is suitable when n is relatively small
You can also sorted (alist) [-N:] Sorted (alist) [: n] for relatively large n
4 Implementing a priority queue
Import HEAPQ class priorityqueue: def __init__ (self): = [] = 0 def push (self, item, priority): Heapq.heappush (self._ Queue, (-priority, Self._index, item )+ = 1 def pop (self): return Heapq.heappop (self._queue) [-1]
5 keys in a field map multiple values Defaultdict
Defaultdict
Defaultdict(list)d[' a ']. Append(1)d[' a ']. Append(2)
d[' B '].append (5)
Python Cookbook-1-data structures and algorithms