python中对象排序的两种方式

很多时候,我们是需要针对对象序列进行排序的,尤其是针对对象的某个属性排序的场景最为常见。以下就实验两种方法来满足这个需求。

1.直接调用序列的sort方法

class Person(object):

    def __init__(self,age,name):
        self.age = age
        self.name = name


def personSort():
    persons = [Person(age,name) for (age,name) in [(12,"lili"),(18,"lulu"),(16,"kaka"),(12,"xixi")]]
    persons.sort(cmp=None,key=lambda x:x.age,reverse=False)
    for element in persons:
        print element.age,":",element.name

person对象里两个字段,一个age,一个name。排序的时候按照age来进行。

2.第二种方式

def operatorSort():
    persons = [Person(age,name) for (age,name) in [(12,"lili"),(18,"lulu"),(16,"kaka"),(12,"xixi")]]
    try:
        import operator
    except ImportError:
        cmpfun = lambda x:x.age
    else:
        cmpfun = operator.attrgetter("age","name")

    persons.sort(key = cmpfun, reverse=False)
    for element in persons:
        print element.age,":",element.name

使用operator模块的attrgetter方法,可以达到同时对几个字段排序的目的。本例中就是先对age字段排序,如果age相等再按name排序。

你可能感兴趣的:(python)