参考1
list.sort(cmp, key, reverse)
- sort是列表的排序函数;
- sorted是python BIF排序函数;
- 使用格式:list.sort(cmp, key, reverse)
- 使用该函数会修改原来的list
# encoding: UTF-8
# s.sort(cmp, key, reverse)
# s.sort(cmp,reverse)
# Author:SXQ
list1 = [['0', 8000, '5'],['1', 8003, '5'], ['2', 8002, '4'], ['3', 8004, '6'], ['4', 8001, '4']]
list2 = [['0', 8000, '5'],['4', 8003, '5'], ['2', 8002, '4'], ['3', 8004, '6'], ['4', 8001, '4']]
# EXP1:list简单排序
list1.sort()
print list1
# EXP2:list简单反向排序
list1.sort(reverse=True)
print list1
list1.sort()
#EXP3:list通过cmp参数反向排序
list1.sort(cmp=lambda x,y:cmp(x[1],y[1]),reverse = True)
print list1
#EXP4:list通过cmp参数排序
list1.sort(cmp=lambda x,y:cmp(x[1],y[1]),reverse = False)
print list1
#EXP5:list通过key参数排序
list1.sort(key=lambda x:x[1])
print list1
#EXP6:list通过key参数反向排序
list1.sort(key=lambda x:x[1],reverse = True)
print list1
#EXP7:list通过key=operator.itemgetter(x)参数反向排序
import operator
list1.sort(key=operator.itemgetter(1))
print list1
#EXP8:list通过key=lambda双次排序
list2.sort(key=lambda x:(x[0],x[1]))
print list2
#EXP9:list通过key=operator.itemgetter(x)参数双次排序
list2.sort(key=operator.itemgetter(1,0))
print list2
list = sorted(list_name,cmp, key, reverse)
- sorted是python BIF排序函数;
- sorted不会更改原来的list,新创建一个排好序列的list
# encoding: UTF-8
# s = sorted(list_name,cmp, key, reverse)
# s = sorted(list_name,cmp,reverse)
# Author:SXQ
list2 = [['0', 8000, '5'],['4', 8004, '5'], ['2', 8002, '4'], ['3', 8004, '6'], ['4', 8001, '4']]
list3 = sorted(list2,key=lambda x:(x[0],x[1]))
print list3
print list2
转载于:https://www.cnblogs.com/lshconfigure/p/5797947.html