Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5025858
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Python/Ruby

2011-03-02 18:08:52

主题:列表(list)和字典(dict)数据排序
环境: winxp pro + sp2 + python2.5
备注: 请注意,凡是在源代码文件中使用了中文字符,请最好保存为utf-8格式

 
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()

  61. 测试:保存为文件,直接执行即可
阅读(1091) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~