0

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

    #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 语句放入priorityQueueLIFO。我该怎么做?

4

2 回答 2

1

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

 priorityQueue.put( (4, (pacman_r-1, pacman_c)) )
于 2014-05-16T03:56:36.160 回答
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产生连续不断增加的整数,我们正在否定它们)。如果队列中两个元组的第一个值相等,则将比较第二个值,并且最近添加的值总是最小的(因此由队列选择)。

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

于 2014-06-04T22:22:44.827 回答