本文实例讲述了Python实现对不原生支持比较操作的对象排序算法。分享给大家供大家参考,具体如下:
问题:想在同一个类的实例之间做排序,但是它们并不原生支持比较操作。
解决方案:使用内建的sorted()
函数可接受一个用来传递可调用对象的参数key,sorted利用该可调用对象返回的待排序对象中的某些值来比较对象。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
from operator import attrgetter class User: def __init__( self , user_id): self .user_id = user_id def __repr__( self ): return 'User({})' . format ( self .user_id) # Example users = [User( 23 ), User( 3 ), User( 99 )] print (users) # Sort it by user-id used lambda表达式 print ( sorted (users,key = lambda r:r.user_id)) # Sort it by user-id used operator.attrgetter() print ( sorted (users, key = attrgetter( 'user_id' ))) |
使用lambda表达式还是operator.attrgetter()
或许只是个人偏好,但是operator.attrgetter()
更快一些,而且具有允许同时提取多个字段值的能力。
这和针对字典的operator.itemgetter()
的使用类似。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
from operator import attrgetter class User: def __init__( self , user_id,fname,lname): self .user_id = user_id self .fname = fname self .lname = lname def __repr__( self ): return 'User({},{},{})' . format ( self .user_id, self .fname, self .lname) # Example users = [User( 23 , 'Brian' , 'Jones' ), User( 3 , 'David' , 'Beazley' ), User( 99 , 'Aig' , 'Jones' )] print (users) # Sort it by lname,fname used operator.attrgetter() print ( sorted (users, key = attrgetter( 'lname' , 'fname' ))) |
1
2
3
4
5
|
>>> = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = RESTART = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = >>> [User( 23 ,Brian,Jones), User( 3 ,David,Beazley), User( 99 ,Aig,Jones)] [User( 3 ,David,Beazley), User( 99 ,Aig,Jones), User( 23 ,Brian,Jones)] >>> |
最后,本节展示的技术同样适用于min()
和max()
这样的函数:
1
2
3
4
5
6
|
>>> min (users,key = attrgetter( 'user_id' )) User( 3 ,David,Beazley) >>> max (users,key = attrgetter( 'user_id' )) User( 99 ,Aig,Jones) >>> max (users,key = attrgetter( 'fname' )) User( 3 ,David,Beazley) |
(代码摘自《Python Cookbook》)
希望本文所述对大家Python程序设计有所帮助。
原文链接:http://www.cnblogs.com/apple2016/p/5747275.html