Python Data StructureQueue in Python - Part 3
Prioritize your queue
PriorityQueue is a type of
queue imported from the module with the same name.
It uses sort order to decide what to retrieve from it first (your object must have a way of comparing its instances):
import queue class Rezha(object): def __init__(self, priority): self.priority = priority def __lt__(self, other): return self.priority > other.priority q = queue.PriorityQueue() q.put(Rezha(11)) q.put(Rezha(55)) q.put(Rezha(100)) while not q.empty(): print(q.get().priority) # output is 100 / 55 / 11
Having defined the
__lt__ method, our PriorityQueue knows now how to sort elements of type