首页 > 代码库 > Python 多级排序

Python 多级排序


class C( object ):
    
    def __init__( self, x1, x2, x3 ):
        self.x1 = x1
        self.x2 = x2
        self.x3 = x3


    def __cmp__( self, other ):
        if self.x1 < other.x1:
            return -1
        elif self.x1 == other.x1:
            if self.x2 < other.x2:
                return -1
            elif self.x2 == other.x2:
                if self.x3 < other.x3:
                    return -1
                elif self.x3 == other.x3:
                    return 0
                else:
                    return 1
            else:
                return 1
        else:
            return 1


    def __repr__( self ):
        return "({x1}, {x2}, {x3})".format( x1 = self.x1,
                                            x2 = self.x2,
                                            x3 = self.x3 )
        

import random

r = random.randint

li = []
for i in xrange( 15 ):
    li.append( C( r( 1, 10 ), r( 1, 10 ), r( 1, 10 ) ) )

for i in li:
    print i

print 

li1 = sorted( li )
for i in li1:
    print i


Python 多级排序