w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
python object list, sort in descending order based on object attribute

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)]




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.