python排序函数

##sort和sorted
相比于sortsorted()的使用更为广泛

sorted(iterable, cmp, key, reverse)
s.sort(cmp, key, reverse)

sorted可以作用域任意迭代对象,而sort()一般作用于列表。

reverse = True表示按照逆序排序

##sorted

sorted排序的关键是传入key

In [35]: students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10), ('michael', 'A', 13), ('mike', 'B', 12), ('jessey', 'C', 15)]

In [36]: students = sorted(students, key=lambda result: result[2], reverse=True)

结果:

In [37]: students
Out[37]:
[('john', 'A', 15),
 ('jessey', 'C', 15),
 ('michael', 'A', 13),
 ('jane', 'B', 12),
 ('mike', 'B', 12),
 ('dave', 'B', 10)]

如果我们对排序有更高的要求,比如在本例中,在按年龄排序之后,我们还希望对年龄相同的同学按照等级进行排序。我们可以这样写key

In [38]: students = sorted(students, key=lambda result: (result[2], result[1]), reverse=True)

In [39]: students
Out[39]:
[('jessey', 'C', 15),
 ('john', 'A', 15),
 ('michael', 'A', 13),
 ('jane', 'B', 12),
 ('mike', 'B', 12),
 ('dave', 'B', 10)]

stackoverflow: Sort a list by multiple attributes?