sort()方法 | sorted()函數 | __call__()方法 | Python

來源:互聯網
上載者:User

標籤:self   __call__   介面   可迭代對象   定義   blog   ted   作用   close   

#     sort()方法與sorted()函數的區別:#     sort()方法是在原可迭代對象直接修改;#     sorted()函數是返回一個新的可迭代對象;# 例子:根據列表中哪個資料更靠近10來排序;# 1.lambda()>> list_first = [1,4,7,9,33,22,55,77]>> list_first.sort(key=lambda x:abs(x-10))>> print(list_first)>> [9, 7, 4, 1, 22, 33, 55, 77]>> list_second = [1,4,7,9,33,22,55,77]>> sorted(list_second, key=lambda x:abs(x-10))>> [9, 7, 4, 1, 22, 33, 55, 77]# 2.自訂函數>> def which_closed(x):>>     return abs(x-10)>> list_first = [1,4,7,9,33,22,55,77]>> list_first.sort(key=which_closed)>> print(list_first)>> [9, 7, 4, 1, 22, 33, 55, 77]# 3.類類比函數 | __call__()>> class WhichClosed(object):>>     def __init__(self,select_num):>>         self.select_num = select_num>>     def __call__(self,x):>>         return abs(x-self.select_num)>> list_first = [1,4,7,9,33,22,55,77]>> list_first.sort(key=WhichClosed(10))>> print(list_first)>> [9, 7, 4, 1, 22, 33, 55, 77]# __call__()作用:使對象變成可調用介面>> class WhichClosed(object):>>     def __init__(self,select_num):>>         self.select_num = select_num>>     def __call__(self,x):>>         return abs(x-self.select_num)>> obj = WhichClosed(10)  # 執行個體化對象>> obj(2)  # 對象加上小括弧時,對象內部調用__call__()方法;>> 8

 

sort()方法 | sorted()函數 | __call__()方法 | Python

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.