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

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

    Readers should notice that the key= method:

    ut.sort(key=lambda x: x.count, reverse=True)
    

    is many times faster than adding rich comparison operators to the objects. I was surprised to read this (page 485 of "Python in a Nutshell"). You can confirm this by running tests on this little program:

    #!/usr/bin/env python
    import random
    
    class C:
        def __init__(self,count):
            self.count = count
    
        def __cmp__(self,other):
            return cmp(self.count,other.count)
    
    longList = [C(random.random()) for i in xrange(1000000)] #about 6.1 secs
    longList2 = longList[:]
    
    longList.sort() #about 52 - 6.1 = 46 secs
    longList2.sort(key = lambda c: c.count) #about 9 - 6.1 = 3 secs
    

    My, very minimal, tests show the first sort is more than 10 times slower, but the book says it is only about 5 times slower in general. The reason they say is due to the highly optimizes sort algorithm used in python (timsort).

    Still, its very odd that .sort(lambda) is faster than plain old .sort(). I hope they fix that.

提交回复
热议问题