both list.sort() and sorted() added a key parameter to specify a FUNCTION to be called on each list element prior to making comparisons.
而且通过通过设置reverse可以颠倒排序结果
#注意key后的是function,不是function call的值, 所以常用lambda表达式
sorted("This is a test string".split(), key=str.lower)
----------------------------------------
['This', 'test', 'string', 'is', 'a']
#A common pattern is to sort complex objects using some of the object’s indices as keys
student_tuples = [('john', 'A', 15),('jane', 'B', 12),('dave', 'B', 10),]
sorted(student_tuples, key=lambda student: student[2])
----------------------------------------
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
#The same technique works for objects with named attributes
class Student(object):
def __init__(self, name, grade, age):
self.name = name
self.grade = grade
self.age = age
def __repr__(self):
return repr((self.name, self.grade, self.age))
student_objects = [Student('John', 'A', 15), Student('Jane', 'B', 12), Student('Dave', 'B', 10),]
sorted(student_objects, key=lambda student: student.age)
------------------------------------------
[('Dave', 'B', 10), ('Jane', 'B', 12), ('John', 'A', 15)]
#上面都可以一些python内置的函数
from operator import itemgetter, attrgetter
sorted(student_tuples, key=itemgetter(2))
sorted(student_objects, key=attrgetter('age'))
sorted(student_tuples, key=itemgetter(1,2))
sorted(student_objects, key=attrgetter('grade', 'age'))