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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值