简体   繁体   中英

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.

为什么不:

lst.sort(key=lambda p: p.job.hours if p.job else 999)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM