字典排序

  1. kids = [
  2. {'name': 'xiaoming', 'score': 99, 'age': 12},
  3. {'name': 'xiaohong', 'score': 75, 'age': 13},
  4. {'name': 'xiaowang', 'score': 88, 'age': 15}
  5. ]
  6. # sorted
  7. sorted(kids, key=lambda x: x['score'])
  8. # 多关键字,相等就往后比较,不等或结束为止
  9. sorted(kids, key=lambda x: (x['score'], x['age']))
  10. # itemgetter
  11. from operator import itemgetter
  12. sorted(kids, key=itemgetter('score'))
  13. # 多关键字
  14. sorted(kids, key=itemgetter('score', 'age'))

对象排序

  1. class Kid:
  2. def __init__(self, name, score, age):
  3. self.name = name
  4. self.score = score
  5. self.age = age
  6. def __repr__(self):
  7. return 'Kid, name: {}, score: {}, age:{}'.format(self.name, self.score, self.age)
  8. from operator import attrgetter
  9. kids = [Kid('xiaoming', 99, 12), Kid('xiaohong', 75, 13), Kid('xiaowang', 88, 15)]
  10. sorted(kids, key=attrgetter('score'))
  11. # 使用lambda来实现
  12. sorted(kids, key=lambda x: x.score)

自定义排序

我们可以在sorted函数的参数当中传入reverse=True来控制是正序还是倒叙,但是如果我使用多关键字,想要按照某个关键字升序,某个关键字降序怎么办

  1. # 先实现自定义元素大小的函数
  2. def cmp(kid1, kid2):
  3. return kid1.age < kid2.age if kid1.score == kid2.score else kid1.score > kid2.score
  4. # 将函数重载为比较类并比较
  5. from functools import cmp_to_key
  6. sorted(kids, key=cmp_to_key(cmp))
  7. # 也可以直接在kid类中重载比较函数,然后直接调用sorted,不用任何其他传参就可以对它进行排序了
  8. class Kid:
  9. def __init__(self, name, score, age):
  10. self.name = name
  11. self.score = score
  12. self.age = age
  13. def __repr__(self):
  14. return 'Kid, name: {}, score: {}, age:{}'.format(self.name, self.score, self.age)
  15. def __lt__(self, other):
  16. return self.score > other.score or (self.score == other.score and self.age < other.age)