linlu11 的博客

(转)python中的排序

 
   1.  # sort.py  
   2. # 这个类用来演示如何对自定义对象进行排序  
   3. class Sortobj:  
   4.     a = 0  
   5.     b = ''  
   6.     def __init__(self, a, b):  
   7.         self.a = a  
   8.         self.b = b  
   9.     def printab(self):  
  10.         print self.a, self.b  
  11.   
  12. # 演示对字符串列表进行排序  
  13. samplelist_str = ['blue','allen','sophia','keen']  
  14. print samplelist_str  
  15. samplelist_str.sort()  
  16. print samplelist_str  
  17.   
  18. print '\n'  
  19.   
  20. # 演示对整型数进行排序  
  21. samplelist_int = [34,23,2,2333,45]  
  22. print samplelist_int  
  23. samplelist_int.sort()  
  24. print samplelist_int  
  25.   
  26. print '\n'  
  27.   
  28. # 演示对字典数据进行排序  
  29. sampledict_str = {'blue':'5555@sina.com',  
  30.                   'allen':'222@163.com',  
  31.                   'sophia':'4444@gmail.com',  
  32.                   'ceen':'blue@263.net'}  
  33. print sampledict_str  
  34. # 按照key进行排序  
  35. print sorted(sampledict_str.items(), key=lambda d: d[0])  
  36. # 按照value进行排序  
  37. print sorted(sampledict_str.items(), key=lambda d: d[1])  
  38.   
  39. # 构建用于排序的类实例  
  40. obja = Sortobj(343, 'keen')  
  41. objb = Sortobj(56, 'blue')  
  42. objc = Sortobj(2, 'aba')  
  43. objd = Sortobj(89, 'iiii')  
  44.   
  45. print '\n'  
  46.   
  47. samplelist_obj = [obja, objb, objc, objd]  
  48. # 实例对象排序前  
  49. for obj in samplelist_obj:  
  50.     obj.printab()  
  51. print '\n'  
  52. # 按照对象的a属性进行排序  
  53. samplelist_obj.sort(lambda x,y: cmp(x.a, y.a))  
  54. for obj in samplelist_obj:  
  55.     obj.printab()  
  56. print '\n'  
  57. # 按照对象的b属性进行排序  
  58. samplelist_obj.sort(lambda x,y: cmp(x.b, y.b))  
  59. for obj in samplelist_obj:  
  60.     obj.printab()  

posted on 2009-12-16 22:32  linlu11  阅读(423)  评论(0编辑  收藏  举报

导航