My Coding >
Programming language >
Python >
Python FAQ >
Python: how to sort list of objects by few parameters
Python: how to sort list of objects by few parametersThis is a very common task, to create procedure, which will sort the list of objects by it’s parameters. But if the first parameters of the object are identical, it will sort by second parameter, and if they are identical, then the comparison will be performed by third parameter. How to make this sorting procedure? It is very easy to do with key parameter and lambda() function. But before, let’s see, how lists are sorted. Sorting the list of listsBy default, in Python the lists are sorted by it’s elements with few following rules:
Let’s check it on this simple example
You can see that:
Sorting of any objects by few parametersAfter studying how lists are sorted, we can convert out task of sorting objects by few parameters into a task of sorting lists with these parameters. lambda() functionThis is a short reminder about lambda() function: lambda L: some_function(L). In this example lambda function take one parameter L and return some results calculated as described in some_function(L)> - this is not necessary function, it can be anything. General expression for sorting by few parametersWe have list lst with objects, which we would like to sort by its parameters, which can be calculated by following function f1(), f2(), f3(), then we can do it this way:
As simple as that! So, we sort the list of parameters, calculated on demand for every element of our list. Example of sorting list by some parametersLet’s sort lists in our list by their sum, length and maximal value.
So, what was happen here? It is very simple to explain:
|
Last 10 artitles
9 popular artitles
|
|
© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit. |