Python3:sorted()函数及列表中的sort()函数
一、sort,sorted函数介绍:
Sort函数是list列表中的函数,而sorted可以对list或者iterator进行排序。
下面我们使用help来查看他们的用法及功能:
sort:
1 >>>help(list.sort) 2 Help on method_descriptor: 3 4 sort(...) 5 L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
sorted:
Python3.x:
1 >>> help(sorted) 2 Help on built-in function sorted in module builtins: 3 4 sorted(iterable, /, *, key=None, reverse=False) 5 Return a new list containing all items from the iterable in ascending order. 6 7 A custom key function can be supplied to customize the sort order, and the 8 reverse flag can be set to request the result in descending order.
Python2.x:
1 >>> help(sorted) 2 Help on built-in function sorted in module __builtin__: 3 4 sorted(...) 5 sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
好吧,Python3.x和Python2.x的sorted函数有点不太一样,少了cmp参数。下面本渣渣主要基于Python2.x的sorted函数进行讲解,Python3.x直接忽略cmp这个参数即可,为了保证代码通用性,不建议大家在今后的编程中使用cmp参数。
二、sort和sorted的比较:
用sort函数对列表排序时会影响列表本身,而sorted不会。
举例:
1 >>> a = [1,2,1,4,3,5] 2 >>> a.sort() 3 >>> a 4 [1, 1, 2, 3, 4, 5] 5 >>> a = [1,2,1,4,3,5] 6 >>> sorted(a) 7 [1, 1, 2, 3, 4, 5] 8 >>> a 9 [1, 2, 1, 4, 3, 5]
Python2.x的sorted函数:sorted(iterable,cmp,key,reverse)
参数:
- iterable可以是list或者iterator;
- cmp是带两个参数的比较函数;
- key 是带一个参数的函数;
- reverse为False或者True;
举例说明:
(1)用cmp函数排序:
1 >>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)] 2 >>> sorted(list1,cmp = lambda x,y: cmp(x[0],y[0])) 3 [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)] 4 >>> sorted(list1,cmp = lambda x,y: cmp(x[1],y[1])) 5 [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
(2)用key函数排序:
1 >>> list1 = [('david', 90), ('mary',90), ('sara',80),('lily',95)] 2 >>> sorted(list1,key = lambda list1: list1[0]) 3 [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)] 4 >>> sorted(list1,key = lambda list1: list1[1]) 5 [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)]
(3)用reverse排序:
1 >>> sorted(list1,reverse = True) 2 [('sara', 80), ('mary', 90), ('lily', 95), ('david', 90)]
(4)用operator.itemgetter函数排序:
1 >>> from operator import itemgetter 2 >>> sorted(list1, key=itemgetter(1)) 3 [('sara', 80), ('david', 90), ('mary', 90), ('lily', 95)] 4 >>> sorted(list1, key=itemgetter(0)) 5 [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
介绍operator.itemgetter函数:
1 >>> import operator 2 >>> a = [1,2,3] 3 >>> b = operator.itemgetter(0) 4 >>> b(a) 5 1
operator.itemgetter函数获取的不是值,而是定义了一个函数。
(5)多级排序:
1 >>> sorted(list1, key=itemgetter(0,1)) 2 [('david', 90), ('lily', 95), ('mary', 90), ('sara', 80)]
- 转载请注明作者和出处:http://blog.csdn.net/u011475210