天天看點

2.隊列操作1.3 保留最後 N 個元素1.4 查找最大或最小的 N 個元素1.4 使用heapq實作優先隊列

隊列操作

  • 1.3 保留最後 N 個元素
  • 1.4 查找最大或最小的 N 個元素
  • 1.4 使用heapq實作優先隊列

1.3 保留最後 N 個元素

可以通過collections.deque進行處理,deque(maxlen=N) 構造函數會建立一個固定大小的隊列。當新的元素加入并且這個隊列已滿的時候, 最老的元素會自動被移除掉。

>>> q = deque(maxlen=3)
>>> q.append(1)
>>> q.append(2)
>>> q.append(3)
>>> q
deque([1, 2, 3], maxlen=3)
>>> q.append(4)
>>> q
deque([2, 3, 4], maxlen=3)
>>> q.append(5)
           

1.4 查找最大或最小的 N 個元素

heapq 子產品有兩個函數:nlargest() 和nsmallest() 可以找出最大或最小的N個元素

import heapq
nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]
print(heapq.nlargest(3, nums)) # Prints [42, 37, 23]
print(heapq.nsmallest(3, nums)) # Prints [-4, 1, 2]
           

1.4 使用heapq實作優先隊列

import heapq

class Item():
    def __init__(self,name):
        self.name = name
    def __repr__(self):
        return 'Item(\'{}\')'.format(self.name)

class PriorityQueue():
    def __init__(self):
        self.queue = []
        self.index=0 #index 變量的作用是保證同等優先級元素的正确排序
        
    def push(self,item,priority):
        heapq.heappush(self.queue,(priority,self.index,item))
        self.index +=1

    def pop(self):
        value = heapq.heappop(self.queue)
        return value[-1]

if __name__ == '__main__':
    q = PriorityQueue()
    q.push(Item('foo'),1)
    q.push(Item('bar'),5)
    q.push(Item('spam'),4)

    print(q.pop()) # 輸出 Item('foo')
           

heapq子產品官方文檔

https://docs.python.org/zh-cn/3.6/library/heapq.html