简体   繁体   English

如何处理优先级队列中具有相同优先级的项目? (蟒蛇)

[英]How to deal with items with the same priority in a priority queue? (Python)

I am trying to create a priority queue, which processes input in this form: 我正在尝试创建一个优先级队列,该队列以这种形式处理输入:

enqueue 2 2
enqueue 1 3
enqueue 5 1
enqueue 6 2
dequeue
dequeue
dequeue
dequeue

I have this code that uses lists: 我有使用列表的代码:

from queue import Queue
data=[]
while True: 
    try:
        operation = input()
    except:
        break
    data.append(operation.split(" "))

data2=[] 
data3=[]
for i in data: #split enqueue and dequeue as not to get an out of range error
    if "enqueue" in i:
        data2.append(i)
    else:
        data3.append(i)

data2=sorted(data2,key=lambda x: int(x[2]))
data2=data2[::-1]

data=data2+data3 #merged the two again after sorting

q=[]

for i in data:
    if "enqueue" in i: #add the item by the already sorted order of priority
        q.append(i[1])
    if "dequeue" in i: #print the first item dequeued before removing it from the queue
        print (q[0])
        del q[0]

My problem with this is that it outputs: 我的问题是它输出:

1
6
2
5

Instead of: (since 2 was technically enqueued before 6, and in the case of items having the same priority, they need to follow the FIFO structure of queues) 代替:(由于技术上2在6之前排入队列,并且对于具有相同优先级的项目,它们需要遵循队列的FIFO结构)

1
2
6
5

Does anyone have any idea on how I can fix this? 有人对我该如何解决有任何想法吗? Is there an alternate way to solve this using queues instead of lists? 是否有其他方法使用队列而不是列表来解决此问题? Thanks! 谢谢!

If you print out 'data2' before sort, after sort, and after data2=data2[::-1] you will see why this is occurring. 如果您在排序之前,排序之后和data2 = data2 [::-1]之后打印出“ data2”,您将了解为什么发生这种情况。

[['enqueue', '2', '2'], ['enqueue', '1', '3'], ['enqueue', '5', '1'], ['enqueue', '6', '2']]
[['enqueue', '5', '1'], ['enqueue', '2', '2'], ['enqueue', '6', '2'], ['enqueue', '1', '3']]
[['enqueue', '1', '3'], ['enqueue', '6', '2'], ['enqueue', '2', '2'], ['enqueue', '5', '1']]

Before you flip it, the sort is just right (ie: elements with the same key are in the order they were input), but reverse of what you want gives you those lists flipped. 在翻转之前,排序是正确的(即:具有相同键的元素按其输入的顺序排列),但是如果您想要的内容相反,则会使这些列表翻转。

Instead of: 代替:

data2=sorted(data2,key=lambda x: int(x[2]))
data2=data2[::-1]

Try: 尝试:

data2=sorted(data2,key=lambda x: int(x[2]), reverse=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM