List进行排序,Python提供了两个方法:
1.用List的成员函数sort进行排序 2.用内建函数sorted进行排序
sort函数:sort(cmp=None, key=None, reverse=False) sorted函数:sorted(iterable, cmp=None, key=None, reverse=False)iterable:是可迭代类型;例如:List cmp:用于比较的函数(大于时返回1,小于时返回-1,等于时返回0),比较什么由key决定,有默认值,迭代集合中的一项; key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项; reverse:排序规则 reverse = True 或者 reverse = False,有默认值。
sort( )函数与sorted( )函数最大的区别是, sort( )函数时对已存在的列表进行操作,调用其没有返回值;而sorted( )函数是返回一个新的list,不在原来的list上进行操作,调用其返回一个排好序的list。
示例:sort( )函数时对已存在的列表进行操作,调用其没有返回值
a = [2, 1, 4, 9, 6] a.sort() print a 输出: [1, 2, 4, 6, 9]示例:sorted( )函数是返回一个新的list,不在原来的list上进行操作,调用其返回一个排好序的list
c = [2, 1, 4, 9, 6] d = sorted(c) print d print c 输出: [1, 2, 4, 6, 9] [2, 1, 4, 9, 6]sorted()函数举例:
1、基于cmp L = [(‘a’, 3), (‘d’, 2), (‘c’, 1), (‘b’, 4)] a = sorted(L, cmp=lambda x, y : cmp(x[0], y[0])) b = sorted(L, cmp=lambda x, y : cmp(x[1], y[1])) print L print a print b 输出: [(‘a’, 3), (‘d’, 2), (‘c’, 1), (‘b’, 4)] [(‘a’, 3), (‘b’, 4), (‘c’, 1), (‘d’, 2)] [(‘c’, 1), (‘d’, 2), (‘a’, 3), (‘b’, 4)] 2、基于key L = [(‘a’, 3), (‘d’, 2), (‘c’, 1), (‘b’, 4)] a = sorted(L, key=lambda x : x[0]) b = sorted(L, key=lambda x : x[1]) print L print a print b 输出: [(‘a’, 3), (‘d’, 2), (‘c’, 1), (‘b’, 4)] [(‘a’, 3), (‘b’, 4), (‘c’, 1), (‘d’, 2)] [(‘c’, 1), (‘d’, 2), (‘a’, 3), (‘b’, 4)] 3、基于reverse L = [2, 1, 4, 9, 6] a = sorted(L, reverse=True) b = sorted(L, reverse=False) print L print a print b 输出: [2, 1, 4, 9, 6] [9, 6, 4, 2, 1] [1, 2, 4, 6, 9]1、函数sorted()不改变原来的list,而是返回一个新的排好序的list。
2、cmp与key均可以采用lambda表达式
3、采用cmp是确定排序方式(如:从大到小还是从小到大),排序的key是函数自己选择;采用key是确定排序的key,排序方式是函数自己选择。
