Home > Net >  Sort a list of different objects in the order that I specify
Sort a list of different objects in the order that I specify

Time:08-19

I have a list of objects like below:

my_list = [LowPriorty(), HighPriority(), HighestPriority(), MediumPriority(), HighestPriority()]

These objects will have a custom defined order, e.g. I could define the order of highest priority to lowest priority like below:

HighestPriority() = should be closest to start of list
HighPriority() = should be second closest to start of the list
MiddlePriority() = should be third closest to start of the list
LowPriority() = should be fourth closest to start of the list
LowestPriority() = should be closest to end of the list

I want to re-order the list based on the priority structure I setup above, so I would expect the sorted list to look like below:

sorted_my_list = [HighestPriority(), HighestPriority(), HighPriority(), MediumPriority(), LowPriority()]

What is the best way to do this? The ordering is going to be based on the class type, but I need to be able to define which class is higher priority.

CodePudding user response:

Another solution:

my_list = [
    LowPriorty(),
    HighPriority(),
    HighestPriority(),
    MediumPriority(),
    HighestPriority(),
]

hierarchy = [HighestPriority, HighPriority, MediumPriority, LowPriorty]

print(sorted(my_list, key=lambda o: hierarchy.index(type(o))))

Prints your sorted list.

CodePudding user response:

You can set a priority for each class with a class variable, which you can later sort by:

class HighestPriority:
    priority = 1
    def __init__(self):
        pass # Other useful code here

class HighPriority:
    priority = 2
    def __init__(self):
        pass # Other useful code here

class MiddlePriority:
    priority = 3
    def __init__(self):
        pass # Other useful code here

And so on... Assuming you now have a list of objects from these classes, sorting them is simple:

result = sorted(list_of_objects, key=lambda x: x.priority)
  • Related