Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: sort specific elements in a list

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.

like image 571
dabadaba Avatar asked Mar 17 '17 09:03

dabadaba


People also ask

How do you sort a list by a specific index in Python?

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.

How do you sort a set of elements in Python?

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.

How do you sort a list in custom order in Python?

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.


1 Answers

Why not:

lst.sort(key=lambda p: p.job.hours if p.job else 999)
like image 141
sureshvv Avatar answered Oct 11 '22 01:10

sureshvv