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(lis
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)]
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.