【问题标题】:Inserting into a priority queue only using the first argument in python仅使用 python 中的第一个参数插入优先级队列
【发布时间】:2014-05-16 03:53:29
【问题描述】:

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

    #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。我该怎么做?

【问题讨论】:

    标签: python queue priority-queue lifo


    【解决方案1】:

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

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

    【讨论】:

    • 我试过了,但它似乎只是使用第二个元组作为优先键,使用字符串的值...我可以让它忽略第二个元组吗?
    • 然后改顺序:priorityQueue.put( ((pacman_r-1, pacman_c), 4) )
    • 然后它使用 "(pacman_r-1, pacman_c)" 字符串作为优先键。
    【解决方案2】:

    如果您希望以 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 的函数,而不是使用queue.PriorityQueue 实例。后者使用heapq 在内部实现其逻辑,但它也做了一堆你可能不需要的锁定(对于单线程代码来说这是毫无意义的开销)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多