仅使用python中的第一个参数插入优先级队列

时间:2014-05-16 03:53:29

标签: python queue priority-queue lifo

如何将项目插入优先级队列,但要确保它只将第一个参数作为优先级。例如:

    #push up
    if((pacman_r != 0 ) and (cellGrid[pacman_r-1][pacman_c].what != '%')):
        priorityQueue.put((4, pacman_r-1, pacman_c))
    #push left 
    if ((pacman_c != 0) and (cellGrid[pacman_r][pacman_c-1].what != '%')):
        priorityQueue.put((4, pacman_r, pacman_c-1))
    #push right
    if ((pacman_c != c) and (cellGrid[pacman_r][pacman_c+1].what != '%')):
        priorityQueue.put((9, pacman_r, pacman_c+1))
    #push down
    if((pacman_r != r ) and (cellGrid[pacman_r+1][pacman_c].what != '%')):
        priorityQueue.put((1, pacman_r+1, pacman_c))

我希望将前两个if语句放入priorityQueue LIFO。我该怎么做?

2 个答案:

答案 0 :(得分:0)

将参数作为单独的元组传递:

 priorityQueue.put( (4, (pacman_r-1, pacman_c)) )

答案 1 :(得分:0)

如果您希望在LIFO订单中返回相同的优先级元素,则应该为您的键添加一个计数值:

# put this with your other import statements
from itertools import count

# put this near where you define your priority queue
counter = count()

#later, add the counter's latest value as a second key value:
#push up
if((pacman_r != 0 ) and (cellGrid[pacman_r-1][pacman_c].what != '%')):
    priorityQueue.put((4, -next(counter), pacman_r-1, pacman_c))
#push left 
if ((pacman_c != 0) and (cellGrid[pacman_r][pacman_c-1].what != '%')):
    priorityQueue.put((4, -next(counter), pacman_r, pacman_c-1))
#push right
if ((pacman_c != c) and (cellGrid[pacman_r][pacman_c+1].what != '%')):
    priorityQueue.put((9, -next(counter), pacman_r, pacman_c+1))
#push down
if((pacman_r != r ) and (cellGrid[pacman_r+1][pacman_c].what != '%')):
    priorityQueue.put((1, -next(counter), pacman_r+1, pacman_c))

这使得您的值为四元组,而不是三元组(因此您需要更新用于访问值的代码)。第二个值将稳步下降(count会永远产生连续增加的整数,我们会否定它们)。如果队列中两个元组的第一个值相等,则将比较第二个值,并且最近添加的一个值将始终最小(并由队列选择)。

顺便说一句,除非您使用队列在多个线程之间同步数据,否则您应该在常规list上使用heapq module的函数,而不是使用{{ 1}}实例。后者使用queue.PriorityQueue在内部实现其逻辑,但它也会执行一些您可能不需要的锁定(对于单线程代码,它是无意义的开销)。