How to sort complex objects with custom criteria in Python
Sorting objects with multiple member variables can be done in multiple ways, such as overloading the “<” operator, using the key parameter and there’s also support to use comparator functions
In most cases, sorting is a simple task but there are occasions when the data is a bit complicated and python provides elegant way to handle those scenarios. So we will look at a complex scenario in this article
1 Object structure
1.1 With class definition
|
|
1.2 As list items
|
|
2 Sort using key parameter
Lets say, our priority is in this order, cpu > ram > ssd
|
|
The result is,
|
|
For simpler cases, when you have only one criteria, you don’t need to use tuples
|
|
3 Operator overloading
Lets make the scenario more complex by introducing Intel,
|
|
If we don’t change anything the result will be,
|
|
Which may not be what we want, we were getting results as expected before because we assumed that
Ryzen 7 > Ryzen 5
which is carried out by the “<” operator of stringFor the sake of demonstration lets define the precedence in this way,
Ryzen 7 > Intel i7 > Ryzen5
Here is one way to achieve this result using operator overloading
|
|
In this function, returning 0 means a is smaller, if 1 is returned then b is smaller
When the “<” operator is defined, you can sort by simply calling
|
|
4 Comparator function
|
|
You can write logic of similar complexity by using comparator function
But in this method, returning -1 or any negative number means a is smaller, if positive number is returned than b is smaller. If 0 is returned then they have the same priority and no swapping will be done
- The benefit of using comparator function is that you don’t overload the class operators and you have the option to use multiple comparators for different use cases.
- If you have already overloaded the “<” operator but a scenario arises where your criteria is a bit different then comparator function is what you may need
5 The smarter way to solve this problem
Use a dictionary to define the priority of the cpu models,
|
|
Then the logic becomes simpler,
|
|
To use comparator function, just replace the less than ("<") operators with minus("-") operator
You may have already guessed that you can make it even simpler without using operator overloading
|
|
This will be the result,
|
|
6 Conclusion
All three ways may have their places but if you can perform the task by using lambda in key parameter than you should stick to that