- bluecrystal
- 等级:


- 性别:
 - 文章: 101
- 积分: 342
- 来自: 成都

|
主题:列表(list)和字典(dict)数据排序
环境: winxp pro + sp2 + python2.5
备注: 请注意,凡是在源代码文件中使用了中文字符,请最好保存为utf-8格式
代码:
python 代码
-
-
- class Sortobj:
- a = 0
- b = ''
- def __init__(self, a, b):
- self.a = a
- self.b = b
- def printab(self):
- print self.a, self.b
-
-
- samplelist_str = ['blue','allen','sophia','keen']
- print samplelist_str
- samplelist_str.sort()
- print samplelist_str
-
- print '\n'
-
-
- samplelist_int = [34,23,2,2333,45]
- print samplelist_int
- samplelist_int.sort()
- print samplelist_int
-
- print '\n'
-
-
- sampledict_str = {'blue':'5555@sina.com',
- 'allen':'222@163.com',
- 'sophia':'4444@gmail.com',
- 'ceen':'blue@263.net'}
- print sampledict_str
-
- print sorted(sampledict_str.items(), key=lambda d: d[0])
-
- print sorted(sampledict_str.items(), key=lambda d: d[1])
-
-
- obja = Sortobj(343, 'keen')
- objb = Sortobj(56, 'blue')
- objc = Sortobj(2, 'aba')
- objd = Sortobj(89, 'iiii')
-
- print '\n'
-
- samplelist_obj = [obja, objb, objc, objd]
-
- for obj in samplelist_obj:
- obj.printab()
- print '\n'
-
- samplelist_obj.sort(lambda x,y: cmp(x.a, y.a))
- for obj in samplelist_obj:
- obj.printab()
- print '\n'
-
- samplelist_obj.sort(lambda x,y: cmp(x.b, y.b))
- for obj in samplelist_obj:
- obj.printab()
测试:保存为文件,直接执行即可
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
返回顶楼 |
|
|