# -*- coding: cp936 -*-
# sort.py
# 这个类用来演示如何对自定义对象进行排序
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'
# 演示对字典数据进行排序
'''
字典实际上并不能排序,我们排的是items,即dict.item(),将字典转换成了一个列表
sorted函数的原型为:
sorted(iterable[, cmp[, key[, reverse]]])
iterable:是可迭代类型类型;
cmp:用于比较的函数,比较什么由key决定,有默认值,迭代集合中的一项;
key:用列表元素的某个属性和函数进行作为关键字,有默认值,迭代集合中的一项;
reverse:排序规则. reverse = True 或者 reverse = False,有默认值。
返回值:是一个经过排序的可迭代类型,与iterable一样。
一般来说,cmp和key可以使用lambda表达式。
常用的形式如下:
sorted(dict.item(), key=lambda e:e[1], reverse=True)
其中e表示dict.item()中的一个元素,e[1]则表示 按 值排序
如果把e[1]改成e[0],那么则是按键排序,reverse=False可以省略
默认为升序排列
'''
sampledict_str = {'blue':'5555@sina.com',
'allen':'222@163.com',
'sophia':'4444@gmail.com',
'ceen':'blue@263.net'}
print sampledict_str
# 按照key进行排序
print sorted(sampledict_str.items(), key=lambda d: d[0])
# 按照value进行排序
print sorted(sampledict_str.items(), key=lambda d: d[1])
# 构建用于排序的类实例
obja = Sortobj(343, 'keen')
objb = Sortobj(56, 'blue')
objc = Sortobj(100, 'aba')
objd = Sortobj(89, 'iiii')
print '\n'
samplelist_obj = [obja, objb, objc, objd]
# 实例对象排序前
for obj in samplelist_obj:
obj.printab()
print '\n'
# 按照对象的a属性进行排序
samplelist_obj.sort(lambda x,y: cmp(x.a, y.a))
for obj in samplelist_obj:
obj.printab()
print '\n'
# 按照对象的b属性进行排序
samplelist_obj.sort(lambda x,y: cmp(x.b, y.b))
for obj in samplelist_obj:
obj.printab()