1 描述
sorted() 函数对所有可迭代的对象进行排序操作。
sorted() 与sort()函数之间的区别
1 排序对象
sorted:所有可迭代对象的排序
sort:list列表的排序
2 返回值
sorted:返回一个新的list
soet:对存在列表操作,返回 self
>>> help(sorted) Help on built-in function sorted in module builtins: sorted(iterable, key=None, reverse=False) Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customise the sort order, and the reverse flag can be set to request the result in descending order.
>>> new_list=[] >>> help(new_list.sort) Help on built-in function sort: sort(...) method of builtins.list instance L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
2 语法
sorted(iterable[, cmp[, key[, reverse]]])
iterable:被排序(可迭代)对象
cmp:比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项。
key:用列表元素的某个属性和函数返回值进行作为关键字,有默认值
reverse:reverse = True 降 , reverse = False 升(默认)。
注;一般来说,cmp 和 key 可以使用 lambda 表达式。
返回值:是一个经过排序的可迭代类型,与iterable一样。
3 示例
3.1 示例1
>>> 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)]
3.2 示例2
l = [2,1,5,-3,7,6,-5,8] s = ['hello','hi','How are you'] print(sorted(l)) #[-5, -3, 1, 2, 5, 6, 7, 8] print(sorted(l,reverse = True)) #[8, 7, 6, 5, 2, 1, -3, -5] print(sorted(l,key = abs,reverse = True)) #[8, 7, 6, 5, -5, -3, 2, 1] print(sorted(s,key = len)) #['hi', 'hello', 'How are you']