python object list, sort in descending order based on object attribute

前端 未结 2 1756
难免孤独
难免孤独 2021-01-21 02:35

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         


        
2条回答
  •  有刺的猬
    2021-01-21 02:51

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

提交回复
热议问题