字典排序
kids = [{'name': 'xiaoming', 'score': 99, 'age': 12},{'name': 'xiaohong', 'score': 75, 'age': 13},{'name': 'xiaowang', 'score': 88, 'age': 15}]# sortedsorted(kids, key=lambda x: x['score'])# 多关键字,相等就往后比较,不等或结束为止sorted(kids, key=lambda x: (x['score'], x['age']))# itemgetterfrom operator import itemgettersorted(kids, key=itemgetter('score'))# 多关键字sorted(kids, key=itemgetter('score', 'age'))
对象排序
class Kid:def __init__(self, name, score, age):self.name = nameself.score = scoreself.age = agedef __repr__(self):return 'Kid, name: {}, score: {}, age:{}'.format(self.name, self.score, self.age)from operator import attrgetterkids = [Kid('xiaoming', 99, 12), Kid('xiaohong', 75, 13), Kid('xiaowang', 88, 15)]sorted(kids, key=attrgetter('score'))# 使用lambda来实现sorted(kids, key=lambda x: x.score)
自定义排序
我们可以在sorted函数的参数当中传入reverse=True来控制是正序还是倒叙,但是如果我使用多关键字,想要按照某个关键字升序,某个关键字降序怎么办
# 先实现自定义元素大小的函数def cmp(kid1, kid2):return kid1.age < kid2.age if kid1.score == kid2.score else kid1.score > kid2.score# 将函数重载为比较类并比较from functools import cmp_to_keysorted(kids, key=cmp_to_key(cmp))# 也可以直接在kid类中重载比较函数,然后直接调用sorted,不用任何其他传参就可以对它进行排序了class Kid:def __init__(self, name, score, age):self.name = nameself.score = scoreself.age = agedef __repr__(self):return 'Kid, name: {}, score: {}, age:{}'.format(self.name, self.score, self.age)def __lt__(self, other):return self.score > other.score or (self.score == other.score and self.age < other.age)
