简体   繁体   中英

Creating a python priority Queue

I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest priority(lowest number) will be pulled out of the queue and when "add function" is called, the new dictionary will be added to the queue and sorted based on its priority number.

Please do help out...

Thanks in advance!

Use the heapq module in the standard library.

You don't specify how you wanted to associate priorities with dictionaries, but here's a simple implementation:

import heapq

class MyPriQueue(object):
    def __init__(self):
        self.heap = []

    def add(self, d, pri):
        heapq.heappush(self.heap, (pri, d))

    def get(self):
        pri, d = heapq.heappop(self.heap)
        return d

This is what I usually present as a side note in some of my patterns talks:

class PriorityQueue(object):
 def __init__(self, key=lambda x: x):
   self.l = []
   self.key = key
 def __len__(self):
   return len(self.l)
 def push(self, obj):
   heapq.heappush(self.l, (self.key(obj), obj))
 def pop(self):
   return heapq.heappop(self.l)[-1]

The OP's requirements are apparently to use operator.itemgetter('priority') as the key argument when instantiating PriorityQueue (needs an import operator at top of module, of course;-).

您可以通过在类中添加dict对象并在其中进行搜索来实现。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM