代码如下:
#encoding=utf-8
print '中国'
#根据对象的属性将对象排序
def sort_by_attr(seq,attr):
intermed=[(getattr(x,attr),i,x) for i,x in enumerate(seq)]
intermed.sort()
return [x[-1] for x in intermed]
def sort_by_attr_inplace(lst,attr):
lst[:]=sort_by_attr(lst,attr)
#DSU内部方式
import operator
def sort_by_attr2(seq,attr):
return sorted(seq,key=operator.attrgetter(attr))
def sort_by_attr_inplace2(lst,attr):
lst.sort(key=operator.attrgetter(attr))
class Person:
def __init__(self,name,pID):
self.name=name
self.pID=pID
def printme(self):
print self.name,self.pID
def printPer(lst):
for per in lst:
per.printme()
lsta=[Person('hyj',1),Person('abc',2),Person('def',3)]
printPer(lsta)
print '-----sort_by_attr'
lstb=sort_by_attr(lsta,'name')
printPer(lstb)
print '-----sort_by_attr_inplace'
sort_by_attr_inplace(lsta,'name')
printPer(lsta)
print '-----sort_by_attr2'
listb=sort_by_attr2(lsta,'pID')
printPer(listb)
print '-----sort_by_attr_inplace2'
sort_by_attr_inplace2(lsta,'pID')
printPer(lsta)
打印结果如下:
中国
hyj 1
abc 2
def 3
-----sort_by_attr
abc 2
def 3
hyj 1
-----sort_by_attr_inplace
abc 2
def 3
hyj 1
-----sort_by_attr2
hyj 1
abc 2
def 3
-----sort_by_attr_inplace2
hyj 1
abc 2
def 3