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

前端 未结 8 2442
北海茫月
北海茫月 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:33

    A way that can be fastest, especially if your list has a lot of records, is to use operator.attrgetter("count"). However, this might run on an pre-operator version of Python, so it would be nice to have a fallback mechanism. You might want to do the following, then:

    try: import operator
    except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
    else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda
    
    ut.sort(key=keyfun, reverse=True) # sort in-place
    

提交回复
热议问题