【问题标题】:priority queue in Python using comparatorPython中使用比较器的优先级队列
【发布时间】:2021-12-27 10:47:40
【问题描述】:

有没有什么方法可以在 Python 中执行 java queue priority comparison.comparingInt 方法?

我希望优先级较高的节点排在队列的最前面。

编辑: 例如:

class node:
  def __init__(self, label, priority):
      self.label = label
      self.priority = priority
  




node1 = node('a', 3)
node2 = node('b',2)
node3 = node('c', 1)
 
nodes in queue comes like this==> (node1,node2,node3)

【问题讨论】:

    标签: python comparator priority-queue


    【解决方案1】:

    正如 Albin 所说,您需要使用 heapq 模块(除非您想从头开始编写自己的堆实现)。需要注意的一件非常重要的事情是,这个库只提供了最小堆的实现,而不是最大堆。

    要为自定义对象编写比较器,您需要重写 __lt__ 函数(使用 < 运算符时调用的函数)。所以你的节点类看起来像这样:

    class node:
      nodes = dict()
    
      def __init__(self, label, priority):
          self.label = label
          self.priority = priority
      
      def __lt__(self, other):
          # Note that we've reversed the operands here, since we want a max-heap.
          return other.priority < self.priority
    

    那么,我们可以如下做一个堆:

    import heapq
    
    heap = []
    
    node1 = node('a', 3)
    node2 = node('b', 2)
    node3 = node('c', 1)
    
    heapq.heappush(heap, node1)
    heapq.heappush(heap, node2)
    heapq.heappush(heap, node3)
    
    # Should print 'a', 'b', 'c' in that order.
    for i in range(3):
        print(heapq.heappop(heap).label)
    

    【讨论】:

    • 感谢朋友,这非常有用(:
    【解决方案2】:

    您应该仔细阅读有关优先级队列的文档(python3 的 heapq): https://docs.python.org/3/library/heapq.html#heapq.heapify

    它指的是优先级队列,并且还有基于元组内的值进行排序的基本示例。

    【讨论】:

    • 我已经编辑了这篇文章。你能再检查一遍吗?!
    猜你喜欢
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    相关资源
    最近更新 更多