« »
2011-06-10Python

90

Python 列表(list)和字典(dict)数据排序

  1. # 这个类用来演示如何对自定义对象进行排序
  2. class Sortobj:
  3.     a = 0
  4.     b = ''
  5.     def __init__(self, a, b):
  6.         self.a = a
  7.         self.b = b
  8.     def printab(self):
  9.         print self.a, self.b
  10.   
  11. # 演示对字符串列表进行排序
  12. samplelist_str = ['blue','allen','sophia','keen']
  13. print samplelist_str
  14. samplelist_str.sort()
  15. print samplelist_str

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

您还可能感兴趣的内容

日志信息 »

该日志于2011-06-10 13:17由 admin 发表在Python分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

没有评论

发表评论 »


返回顶部