sort 与 sorted 区别:
sorted(iterable[, cmp[, key[, reverse]]])
返回重新排序的列表。
>>>> a = [5,7,6,3,4,1,2] >>>> b = sorted(a) # 保留原列表 >>>> a [5, 7, 6, 3, 4, 1, 2] >>>> b [1, 2, 3, 4, 5, 6, 7] >>>> L=[('b',2),('a',1),('c',3),('d',4)] >>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # 利用cmp函数 [('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>> sorted(L, key=lambda x:x[1]) # 利用key >[('a', 1), ('b', 2), ('c', 3), ('d', 4)] >>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>>> sorted(students, key=lambda s: s[2]) # 按年龄排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>>> sorted(students, key=lambda s: s[2], reverse=True) # 按降序 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>>
>>>>l:[('a', 1), ('b', 2), ('e', 3), ('d', 4), ('c', 6)] >>>>l.sort(key=lambda x : x[1], reverse=True) >>>>l:[('c', 6), ('d', 4), ('e', 3), ('b', 2), ('a', 1)]