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

前端 未结 2 1782
难免孤独
难免孤独 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:53

    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.

提交回复
热议问题