python sort、sorted

1.

(1).sorted()方法返回一个新列表(默认升序)。

python sort、sorted

list.sort()

python sort、sorted

(2).另一个不同:list.sort()方法仅被定义在list中,sorted()方法对所有的可迭代序列都有效。

python sort、sorted

2.key参数/函数

从python2.4开始,在list.sort()和sorted()增加了key参数,key在每个元素比较浅被调用。

例如:通过key指定的函数来忽略字符串大小写:

python sort、sorted

通过复杂对象的某些值来对复杂对象的序列进行排序:

(1).

python sort、sorted

(2).对字典进行排序:

python sort、sorted

对拥有命名属性的复杂对象进行排序:

python sort、sorted

3.Operator模块函数

operator模块有itemgetter, attrgetter,从2.6开始增加了methodcaller方法。

python sort、sorted

operator允许多级的排序:先以grade,再以age排序

python sort、sorted

4.升序和降序

list.sort()和sorted()都接受一个参数reverse(True or False)来表示升序或降序。

python sort、sorted

5.排序的稳定性和复杂性

多个元素有相同的key,则排序前后他们的先后顺序不变。

python sort、sorted

注意:排序后"blue"的顺序被保持住了,即(‘blue’, 1)在('blue', 2)的前面。

构建多个步骤进行更复杂的排序:对student数据先以grade降序排列,再以age升序排列

python sort、sorted