Python排序函数sort()和sorted()详解 |
您所在的位置:网站首页 › Python中sort函数 › Python排序函数sort()和sorted()详解 |
我们需要对List进行排序,Python提供了两个方法 对给定的List L进行排序, 方法1.用List的成员函数sort进行排序
方法2.用内建函数sorted进行排序(从python 2.4开始) sort函数定义:sort(cmp=None, key=None, reverse=False) sorted函数定义:sorted(iterable, cmp=None, key=None, reverse=False)
参数解析: iterable:是可迭代类型; cmp:用于比较的函数(大于时返回1,小于时返回-1,等于时返回0),比较什么由key决定,有默认值,迭代集合中的一项; key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项; reverse:排序规则. reverse = True 或者 reverse = False,有默认值。
注:sort( )函数与sorted( )函数最大的区别是, sort( )函数时对已存在的列表进行操作,调用其没有返回值;而sorted( )函数是返回一个新的list,不在原来的list上进行操作,调用其返回一个排好序的list。
示例1: a = [2, 1, 4, 9, 6] a.sort() print a c = [2, 1, 4, 9, 6] d = sorted(c) print d print c输出: [1, 2, 4, 6, 9] [1, 2, 4, 6, 9] [2, 1, 4, 9, 6]
示例1是采用函数默认的设置,对于排序参数设置,主要有以下三种:基于cmp;基于key;基于reverse。 下面仅以sorted()函数举例,sort()函数可以参考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,排序方式是函数自己选择。
参考链接: http://blog.csdn.net/zyl1042635242/article/details/43115675 http://www.cnblogs.com/65702708/archive/2010/09/14/1826362.html http://www.cnblogs.com/kellyseeme/p/5525052.html
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |