5

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.

1
  • 1
    I find your way of doing Pythonic enough. You do not need the second list but other than that.. Commented Mar 17, 2017 at 9:26

1 Answer 1

7

Why not:

lst.sort(key=lambda p: p.job.hours if p.job else 999)
Sign up to request clarification or add additional context in comments.

10 Comments

Does this solution keep the order for people without job?
Wait, now that I think about it, wouldn't this solution position the people without job at the beginning of the list, and not at the end as it is intended?
@dabadaba No, because of the minus sign -p.job.hours.
@dabadaba, yes you could avoid the sentinal by using a key pair: lst.sort(key=lambda p: (not p.job, p.job.hours if p.job else 0)) would sort the ones with a job first then the others and the 0 could be any constant value.
@dabadaba if makes the sort key a tuple The first element is False if p.job is set, True if p.job is not set so all the people with jobs sort first, then the ones without jobs. The second element then acts as a secondary key and sorts in order of the number of hours but only when needed to break the tie on the first element.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.