Python Cookbook 5.7 增加元素时候保持序列顺序
# -*- coding: utf-8 -*- # [1] Python Cookbook 5.7 增加元素时候保持序列顺序 # [2] http://s99f.blog.163.com/blog/static/351183652010111602517298/ import heapq import random rand = random.sample(range(10), 10) # 生成随机整数列表 print rand # >>> [7, 4, 1, 3, 8, 5, 9, 0, 2, 6] heap = [] for x in rand: heapq.heappush(heap, x) print [heapq.heappop(heap) for i in range(len(heap))] # >>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 可以用heapify函数对列表堆化 heapq.heapify(rand) print rand # >>> [0, 2, 1, 3, 6, 5, 9, 7, 4, 8] # Python Cookbook 5.7节实现了一个优先级队列 class prioq: def __init__(self): self.q = [] self.i = 0 #计数器, 如果cost一样, 则先来的元素优先级高 def push(self, item, cost): # cost越大, 优先级越高 heapq.heappush(self.q, (-cost, self.i, item)) self.i += 1 def pop(self): return heapq.heappop(self.q)[-1] rand = random.sample(range(10), 10) # 生成随机整数列表 print rand # >>> [1, 4, 3, 5, 6, 0, 7, 2, 8, 9] q = prioq() for i, x in enumerate(rand): q.push(x, i) # 用索引模拟优先级 print[ q.pop() for i in range(len(q.q))] # >>> [9, 8, 2, 7, 0, 6, 5, 3, 4, 1]