简体   繁体   English

如何对列表列表进行排序以保留优先级最高的项目? (蟒蛇)

[英]How do I sort a list of list to retain the item with the highest priority? (Python)

I am trying to make a Priority Queue that takes in input that contains a dequeue or enqueue operation then the value followed by the priority might look like: 我试图制作一个优先队列,该队列接受包含出队或入队操作的输入,然后优先级后面的值可能类似于:

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

I have this code at the start that sorts this by the order of priority: 我在开始时有以下代码,按优先级对其进行排序:

from queue import Queue

data=[]
while True: 
    operation = input()
    if operation == "":
        break
    data.append(operation.split(" "))

data2=[]
data3=[]
for i in data: #separated into two list as not to get an out of range error when sorting 
    if "enqueue" in i: 
         data2.append(i)
    else:
         data3.append(i)


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

data2=data2[::-1] #reversed to make it easier to order it by the highest priority

data=data2+data3 #put the enqueue and dequeue inputs together again

q=[]

for i in data:
    if "enqueue" in i: #add to the queue by priority
        q.append(i[1])
    if "dequeue" in i: #dequeue by priority
        print (q[0])
        del q[0]

My problem right now is that in the case of having the same priority, it should follow the first-in-first-out principle but since I sorted it, the initial order got lost. 我现在的问题是,在具有相同优先级的情况下,它应该遵循先进先出的原则,但是由于我对它进行了排序,所以最初的顺序已经丢失了。 So I would have a list like: 所以我会有一个像这样的列表:

So I would have a list like: 所以我会有一个像这样的列表:

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

And it would output: 它会输出:

1
6
2
5

Instead of: 代替:

1
2
6
5

How can I change the sorting such that it sorts the items by the highest priority but keep the initial order of those with the same priority? 如何更改排序方式,使其以最高优先级对项目进行排序,但保持相同优先级的项目的初始顺序? Thank you in advance. 先感谢您。

To solve your problem, instead of reversing data2 after sorting, add the parameter reverse = True to your sorted call. 为了解决您的问题,而不是在排序后反转data2 ,而是将参数reverse = True添加到已sorted调用中。

This happens because python sorting is stable, and will keep the original order when sorting. 发生这种情况是因为python排序是稳定的,并且在排序时会保持原始顺序。 If you reverse the list after sorting, it will also reverse the original order. 如果您排序反转列表,它也会反转原始顺序。

>>> data2 = sorted(data2, key = lambda x: int(x[2]), reverse = True)
>>> print(data2)
[['enqueue', '1', '3'], ['enqueue', '2', '2'], ['enqueue', '6', '2'], ['enqueue', '5', '1']]

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

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