list.sort

参考1

list.sort(cmp, key, reverse)

  • sort是列表的排序函数;
  • sorted是python BIF排序函数;
  • 使用格式:list.sort(cmp, key, reverse)
  • 使用该函数会修改原来的list
  1. # encoding: UTF-8
  2. # s.sort(cmp, key, reverse)
  3. # s.sort(cmp,reverse)
  4. # Author:SXQ
  5. list1 = [['0', 8000, '5'],['1', 8003, '5'], ['2', 8002, '4'], ['3', 8004, '6'], ['4', 8001, '4']]
  6. list2 = [['0', 8000, '5'],['4', 8003, '5'], ['2', 8002, '4'], ['3', 8004, '6'], ['4', 8001, '4']]
  7. # EXP1:list简单排序
  8. list1.sort()
  9. print list1
  10. # EXP2:list简单反向排序
  11. list1.sort(reverse=True)
  12. print list1
  13. list1.sort()
  14. #EXP3:list通过cmp参数反向排序
  15. list1.sort(cmp=lambda x,y:cmp(x[1],y[1]),reverse = True)
  16. print list1
  17. #EXP4:list通过cmp参数排序
  18. list1.sort(cmp=lambda x,y:cmp(x[1],y[1]),reverse = False)
  19. print list1
  20. #EXP5:list通过key参数排序
  21. list1.sort(key=lambda x:x[1])
  22. print list1
  23. #EXP6:list通过key参数反向排序
  24. list1.sort(key=lambda x:x[1],reverse = True)
  25. print list1
  26. #EXP7:list通过key=operator.itemgetter(x)参数反向排序
  27. import operator
  28. list1.sort(key=operator.itemgetter(1))
  29. print list1
  30. #EXP8:list通过key=lambda双次排序
  31. list2.sort(key=lambda x:(x[0],x[1]))
  32. print list2
  33. #EXP9:list通过key=operator.itemgetter(x)参数双次排序
  34. list2.sort(key=operator.itemgetter(1,0))
  35. print list2

list = sorted(list_name,cmp, key, reverse)

  • sorted是python BIF排序函数;
  • sorted不会更改原来的list,新创建一个排好序列的list
  1. # encoding: UTF-8
  2. # s = sorted(list_name,cmp, key, reverse)
  3. # s = sorted(list_name,cmp,reverse)
  4. # Author:SXQ
  5. list2 = [['0', 8000, '5'],['4', 8004, '5'], ['2', 8002, '4'], ['3', 8004, '6'], ['4', 8001, '4']]
  6. list3 = sorted(list2,key=lambda x:(x[0],x[1]))
  7. print list3
  8. print list2




posted @ 2016-08-23 09:08  lshconfigure  阅读(224)  评论(0编辑  收藏  举报