【问题标题】:Python: clear items from PriorityQueuePython:从 PriorityQueue 中清除项目
【发布时间】:2016-11-28 09:11:24
【问题描述】:

Clear all items from the queue

我看了上面的答案

我正在使用 python 2.7

import Queue
pq = Queue.PriorityQueue()
pq.clear()

我收到以下错误:

AttributeError: PriorityQueue instance has no attribute 'clear'

有没有办法轻松清空优先队列而不是手动弹出所有项目?还是会重新实例化工作(即它不会与 join() 混淆)?

【问题讨论】:

  • 链接的答案建议使用pg.queue.clear()
  • pq.queue.clear() AttributeError: 'list' object has no attribute 'clear'
  • @Evert 仍然错误
  • .queue 没有记录在 Queue() 中,所以我怀疑这有点像 hack,并且(显然)不能依赖。请参阅 Kristof 的回答。
  • 您确定需要使用Queue 模块吗?它不是通用的数据结构,而是专门用于线程之间的同步通信。如果您不需要同步而只需要一个通用的 LIFO 队列,请使用collections.deque。对于不同步的优先级队列,使用listheapq 模块中的函数。

标签: python python-2.7 priority-queue


【解决方案1】:

实际上是pq.queue.clear()。但是,正如您引用的问题的答案中所述,这没有记录并且可能不安全。

最干净的方式在this answer中描述:

while not q.empty():
    try:
        q.get(False)
    except Empty:
        continue
    q.task_done()

当然,重新实例化队列也可以工作(对象会简单地从内存中删除),只要代码的其他部分没有保留对旧队列的引用。

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2023-03-15
    相关资源
    最近更新 更多