How to sort a list of objects based on an attribute of the objects?

前端 未结 8 2456
北海茫月
北海茫月 2020-11-21 23:30

I\'ve got a list of Python objects that I\'d like to sort by an attribute of the objects themselves. The list looks like:

>>> ut
[,         


        
8条回答
  •  星月不相逢
    2020-11-22 00:31

    # To sort the list in place...
    ut.sort(key=lambda x: x.count, reverse=True)
    
    # To return a new list, use the sorted() built-in function...
    newlist = sorted(ut, key=lambda x: x.count, reverse=True)
    

    More on sorting by keys.

提交回复
热议问题