首先介绍sort
sort,顾名思义,是一个排序函数,它用
sort(list)
方式使用,将原列表排序。
让我们试试实例:
>>>a=[1,2,1,4]
>>>a
[1, 2, 1, 4]
>>>sort(a)
>>>a
[1, 1, 2, 4]
>>>a[0]
1
>>>a[1]=2
>>>a
[1, 2, 2, 4]
>>>a[3]=12
>>>sort(a)
[1, 2, 4, 12]
然后介绍sorted
sorted和sort一样,但是不改变原列表,返回排序后列表。
让我们试试实例:
>>>a=[1,3,7,5]
>>>sorted(a)
[1, 3, 5, 7]
>>>b=[1,9,3,6]
>>>a=sorted(b)
>>>a
[1, 3, 6, 9]
sorted还有其他用法,实例:
>>>from operator import itemgetter
>>>stu=[('a',0),('b',40),('c',100),('d',80)]
>>>sorted(stu,cmp = lambda x,y: cmp(x[0],y[0])) #首字母排序
[('a', 0), ('b', 40), ('c', 100), ('d', 80)]
>>>sorted(stu,cmp = lambda x,y: cmp(x[1],y[1])) #得分排序
[('a', 0), ('b', 40), ('d', 80), ('c', 100)]
>>>sorted(list1,key = lambda stu: stu[0]) #首字母排序
[('a', 0), ('b', 40), ('c', 100), ('d', 80)]
>>>sorted(list1,key = lambda stu: stu[1]) #得分排序
[('a', 0), ('b', 40), ('d', 80), ('c', 100)]
>>>sorted(stu,cmp = lambda x,y: cmp(x[0],y[0]),reverse=True) #首字母反向排序
[('d', 80), ('c', 100), ('b', 40), ('a', 0)]
>>>sorted(list1,key = itemgetter(0)) #首字母排序
'a', 0), ('b', 40), ('c', 100), ('d', 80)]
>>>sorted(list1,key = itemgetter(1)) #得分排序
[('a', 0), ('b', 40), ('d', 80), ('c', 100)]
>>>sut2=[('a',5),('a',4),('b',0)]
>>>sorted(list1,key = itemgetter(0,1)) #双关键字排序
[('a', 4), ('a', 5), ('b', 0)]