Python cookbook(資料結構與演算法)實現對不原生支援比較操作的對象排序演算法樣本,pythoncookbook

來源:互聯網
上載者:User

Python cookbook(資料結構與演算法)實現對不原生支援比較操作的對象排序演算法樣本,pythoncookbook

本文執行個體講述了Python實現對不原生支援比較操作的對象排序演算法。分享給大家供大家參考,具體如下:

問題:想在同一個類的執行個體之間做排序,但是它們並不原生支援比較操作。

解決方案:使用內建的sorted()函數可接受一個用來傳遞可調用對象的參數key,sorted利用該可調用對象返回的待排序對象中的某些值來比較對象。

from operator import attrgetterclass User:  def __init__(self, user_id):    self.user_id = user_id  def __repr__(self):    return 'User({})'.format(self.user_id)# Exampleusers = [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()的使用類似。

from operator import attrgetterclass 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)# Exampleusers = [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')))
>>> ================================ 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()這樣的函數:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.