# Python应用——自定义排序全套方案

## 字典排序

``````kids = [
{'name': 'xiaoming', 'score': 99, 'age': 12},
{'name': 'xiaohong', 'score': 75, 'age': 13},
{'name': 'xiaowang', 'score': 88, 'age': 15}
]

``````sorted(kids, key=lambda x: x['score'])

``````sorted(kids, key=lambda x: (x['score'], x['age']))

## itemgetter

``````from operator import itemgetter

sorted(kids, key=itemgetter('score'))

``````sorted(kids, key=itemgetter('score', 'age'))

## 对象排序

``````class Kid:
def __init__(self, name, score, age):
self.name = name
self.score = score
self.age = age

def __repr__(self):
return 'Kid, name: {}, score: {}, age:{}'.format(self.name, self.score, self.age)

``````from operator import attrgetter

kids = [Kid('xiaoming', 99, 12), Kid('xiaohong', 75, 13), Kid('xiaowang', 88, 15)]

sorted(kids, key=attrgetter('score'))

``````sorted(kids, key=lambda x: x.score)

## 自定义排序

``````def cmp(kid1, kid2):
return kid1.age < kid2.age if kid1.score == kid2.score else kid1.score > kid2.score

``````def cmp(kid1, kid2):
if kid1.score == kid2.score:
return kid1.age < kid2.age
else:
return kid1.score > kid2.score

``````from functools import cmp_to_key

sorted(kids, key=cmp_to_key(cmp))

``````def cmp_to_key(mycmp):
"""Convert a cmp= function into a key= function"""
class K(object):
__slots__ = ['obj']
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
__hash__ = None
return K

``````class Kid:
def __init__(self, name, score, age):
self.name = name
self.score = score
self.age = age

def __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)