I have a list of elements I want to sort, but I don't want to sort all of them, only those with a particular state. For example, let's say I have a list of peole:
lst = [Mary, John, Anna, Peter, Laura, Lisa, Steve]
Some of them have a job, let's say [Anna, Lisa, Steve]
. I want to sort (ascending) these by the number of hours they work and move them to the beginning of the list, while keeping the rest in the exact same order. So let's say the number of hours they work is the following:
Anna.job.hours # 10
Lisa.job.hours # 5
Steve.job.hours # 8
After the partial sort the list would look like this:
[Lisa, Steve, Anna, Mary, John, Peter, Laura]
Of course I could create two new lists out of the original one, sort the one I want to sort and the put them together again to achieve what I am after:
with_job = [person for person in lst if person.job]
without_job = [person for person in lst if not person.job]
with_job.sort(key=lambda p: p.job.hours)
lst = with_job + without_job
But I wonder if there is a straigthforward, Pythonic way of doing this.
The function sorted() is used to sort a list in Python. By default, it sorts the list in ascending order. The function itemgetter() from the operator module takes an index number as a parameter and returns the element from the data set placed at that index number.
Sort() Method This method sorts the list in ascending order by default, and we can use the reverse parameter to sort in descending order. This method changes the original list and doesn't return anything.
Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.
Why not:
lst.sort(key=lambda p: p.job.hours if p.job else 999)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With