简体   繁体   English

如果第一个属性相同,则按多个属性对对象列表进行排序

[英]Sorting list of objects by more than one attribute if the first attribute is the same

I want to sort by Arrival time for first come first serve scheduling algorithm.我想按到达时间排序先到先得调度算法。 However, if multiple arrival times are the same value, I want to sort them by PID.但是,如果多个到达时间是相同的值,我想按 PID 对它们进行排序。

So, with input所以,有输入

PID, Arrival Time, Burst time PID、到达时间、突发时间
3,0,3 3,0,3
2,0,5 2,0,5
1,9,8 1,9,8
4,10,6 4,10,6

It should produce PID, Arrival Time, Burst time它应该产生PID,到达时间,突发时间
2,0,5 2,0,5
3,0,3 3,0,3
1,9,8 1,9,8
4,10,6 4,10,6

class Process: class 工艺:
def init (self, ID, ArrivalTime, BurstTime): def init (self, ID, ArrivalTime, BurstTime):
self.ID = ID自我.ID = ID
self.ArrivalTime = ArrivalTime self.ArrivalTime = 到达时间
self.BurstTime = BurstTime self.BurstTime = BurstTime

Here is the lambda function I am using to sort by Arrival time.这是我用来按到达时间排序的 lambda function。

sortedProcesses = sorted(processes, key=lambda x: x.ArrivalTime) sortedProcesses = sorted(进程,key=lambda x: x.ArrivalTime)

How can I sort by arrival time mainly, and sort by PID if the arrival times are the same?如何主要按到达时间排序,如果到达时间相同则按PID排序?

You can use tuples as sort keys so you can make your lambda function return a tuple with the higher priority sort order fields appearing first.您可以使用元组作为排序键,这样您就可以使您的 lambda function 返回一个具有较高优先级排序顺序字段的元组首先出现。

 sortedProcesses = sorted(processes, key=lambda x: (x.x.ArrivalTime,x.ID))

If you need an inverted sort for one of the properties, you can leverage the fact that Python's sort is stable.如果您需要对其中一个属性进行倒排,您可以利用 Python 的排序是稳定的这一事实。 To do this, sort by the lowest priority field first and the resort the result by the higher priority one.为此,首先按优先级最低的字段排序,然后按优先级较高的字段排序结果。

For example, if you want the items in reverse arrival time but in ascending ID order for the same arrival time:例如,如果您希望项目以相反的到达时间但在相同的到达时间以升序的 ID 顺序排列:

 sortedProcesses = sorted(processes, key=lambda x: x.ID)
 sortedProcesses = sorted(sortedProcesses, key=lambda x: x.ArrivalTime, reverse=True)

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

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