python內置排序方式有兩種,一種是針對列表的.sort()方法,另一種是sorted()函數,他們方法相似,區別有兩點python
一、list.sort()方法只適合列表對象,sorted()函數適合任何可迭代對象。函數
二、list.sort()用於改變當前列表,sorted()返回一個新的序列。ui
用法示例:code
>>>help(sorted) Help on built-in function sorted in module builtins: sorted(...) sorted(iterable, key=None, reverse=False) --> new sorted list >>>ls = [5,1,9,7] >>> sorted(ls) [1, 5, 7, 9] >>>ls.sort() >>>ls [1, 5, 7, 9] #逆序 >>ls.sort(reverse = True) >>>ls [9,7,5,1]
經過key函數指定排序方法:(由於sort()和sorted()功能相似,以後都使用sorted()示例)對象
#假定有個學生年級、年齡名單 >>>students = {'mhye':(2,18),'Jackey':(3,15),'Lucy':(1,16)} #若是想要按年級排序 >>>sorted(students.items(),key = lambda x:x[1][0]) [('Lucy', (1, 16)), ('mhye', (2, 18)), ('Jackey', (3, 15))] >>>sorted(students.items(),key = lambda x:x[1][0]) [('Jackey', (3, 15)), ('Lucy', (1, 16)), ('mhye', (2, 18))] #這個例子不算太好,不夠直觀,下面這個略微直觀點 >>>students=[('mhye',2,18),('Jackey',3,15),('Lucy',1,16)] >>>sorted(students,key = lambda x : x[2]) [('Jackey', 3, 15), ('Lucy', 1, 16), ('mhye', 2, 18)]
經過對象的屬性進行排序,實例化的類按照屬性進行排序排序
>>>class student(): def __init__(self,name,grade,age): self.name = name self.age = age self.grade = grade def __repr__(self): return repr((self.name,self.grade,self.age)) def grade_age(self): return self.grade/self.age >>>data =(student('mhye',2,24),student('Jackey',1,17),student('Lucy',3,5)) >>>sorted(data,key =lambda student:student.grade) [('Jackey', 1, 17), ('mhye', 2, 24), ('Lucy', 3, 5)]
python內置的operater模塊中,itemgetter,attrgetter,methodcaller方法能夠用來對對象,屬性,方法進行調用用於排序索引
>>>from operator import attrgetter,itemgetter,methodcaller >>>sorted(data,key = attrgetter('age')) [('Lucy', 3, 5), ('Jackey', 1, 17), ('mhye', 2, 24)] In [66]: sorted(data2,key = itemgetter(2)) Out[66]: [('Lucy', 3, 5), ('Jackey', 1, 17), ('mhye', 2, 24)] #itemgetter只支持可索引對象 >>>data2 = (('mhye', 2, 24), ('Jackey', 1, 17), ('Lucy', 3, 5)) >>>sorted(data2,key = itemgetter(2))#以年齡排序 [('Lucy', 3, 5), ('Jackey', 1, 17), ('mhye', 2, 24)] <<<sorted(data2,key = itemgetter(0,1))#以姓名、年級排序 [('Jackey', 1, 17), ('Lucy', 3, 5), ('mhye', 2, 24)] sorted(data,key = methodcaller('grade_age')) [('Jackey', 1, 17), ('mhye', 2, 24), ('Lucy', 3, 5)]