【问题标题】:Removing an arbitrary item from the priority queue从优先级队列中删除任意项目
【发布时间】:2012-03-06 11:06:54
【问题描述】:

如何从优先级队列中删除任意项目。假设我有一个作业优先队列。我有一份工作要“取消”,所以我需要将其从队列中删除,我该怎么做?

更新

添加一个相关问题:https://stackoverflow.com/a/9288081/292291

【问题讨论】:

    标签: python python-3.x queue


    【解决方案1】:

    我假设您使用的是heapqdocumentation对这个问题有这样的说法,这似乎很合理:

    剩下的挑战围绕着寻找待处理的任务和 更改其优先级或完全删除它。寻找任务 可以通过指向队列中条目的字典来完成。

    删除条目或更改其优先级更加困难,因为 它会破坏堆结构不变量。所以,一个可能的解决方案 是将现有条目标记为已删除并添加一个新条目 修改优先级。

    文档提供了一些基本的示例代码来展示如何做到这一点,我在这里逐字复制:

    pq = []                         # list of entries arranged in a heap
    entry_finder = {}               # mapping of tasks to entries
    REMOVED = '<removed-task>'      # placeholder for a removed task
    counter = itertools.count()     # unique sequence count
    
    def add_task(task, priority=0):
        'Add a new task or update the priority of an existing task'
        if task in entry_finder:
            remove_task(task)
        count = next(counter)
        entry = [priority, count, task]
        entry_finder[task] = entry
        heappush(pq, entry)
    
    def remove_task(task):
        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        entry = entry_finder.pop(task)
        entry[-1] = REMOVED
    
    def pop_task():
        'Remove and return the lowest priority task. Raise KeyError if empty.'
        while pq:
            priority, count, task = heappop(pq)
            if task is not REMOVED:
                del entry_finder[task]
                return task
        raise KeyError('pop from an empty priority queue')
    

    【讨论】:

      【解决方案2】:

      Python 内置的PriorityQueue 不支持移除除顶部之外的任何项目。如果您需要任何项目删除支持,您需要实现自己的队列(或查找其他人的实现)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        • 2019-03-19
        • 1970-01-01
        • 2011-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多