3

I have a list of objects, which I need to sort by one of the objects attributes.

I can sort in ascending order with the following code

list1 = sorted(list1, key=lambda object1: object1.fitness)

However, this sorts the list by ascending order and what I need to do is sort by descending. Is this possible when sorting a list of objects?

2
  • 1
    operator.attrgetter instead of a lambda might also be useful Commented Apr 3, 2014 at 14:59
  • @SethMMorton thanks! included into the answer. Commented Apr 3, 2014 at 15:06

2 Answers 2

15

Specify reverse=True argument:

list1 = sorted(list1, key=lambda object1: object1.fitness, reverse=True)

Demo (simple list of integers):

>>> l = [6, 0, 2, 3, 1, 5, 4]
>>> sorted(l)
[0, 1, 2, 3, 4, 5, 6]
>>> sorted(l, reverse=True)
[6, 5, 4, 3, 2, 1, 0]

Demo (datetime.dates, using operator.attrgetter instead of lambda as @SethMMorton suggested):

>>> from datetime import date
>>> from operator import attrgetter
>>> l = [date(2014, 4, 11), date(2014, 4, 2), date(2014, 4, 3), date(2014, 4, 8)]

>>> sorted(l, key=attrgetter('day'))
[datetime.date(2014, 4, 2), 
 datetime.date(2014, 4, 3), 
 datetime.date(2014, 4, 8), 
 datetime.date(2014, 4, 11)]
>>> sorted(l, key=attrgetter('day'), reverse=True)
[datetime.date(2014, 4, 11), 
 datetime.date(2014, 4, 8), 
 datetime.date(2014, 4, 3), 
 datetime.date(2014, 4, 2)]
Sign up to request clarification or add additional context in comments.

2 Comments

another alternative is using cmp_to_key helper function and creating your own object comparator
Perfect, cheers! just got to wait 6 mins before I can accept the answer haha
0

See this link to craete your own comparator. You can even compare by multiple attributes or complex logic.

It works as this: cmp_to_key expects a function giving key = cmp_to_key(obj) where obj is an object to be sorted. Finally an object implementing comparator operators is returned, and can be used so you can do any custom comparisson logic.

Comments

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.