简体   繁体   中英

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.

So, with input

PID, Arrival Time, Burst time
3,0,3
2,0,5
1,9,8
4,10,6

It should produce PID, Arrival Time, Burst time
2,0,5
3,0,3
1,9,8
4,10,6

class Process:
def init (self, ID, ArrivalTime, BurstTime):
self.ID = ID
self.ArrivalTime = ArrivalTime
self.BurstTime = BurstTime

Here is the lambda function I am using to sort by Arrival time.

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

How can I sort by arrival time mainly, and sort by PID if the arrival times are the same?

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.

 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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