Sort () method | Sorted () function | __call__ () method | Python

Source: Internet
Author: User

#the sort () method differs from the sorted () function:#the sort () method is modified directly in the original iteration object;#The sorted () function returns a new object that can be iterated;#Example: Sort by which data in the list is closer to 10来;#1.lambda ()>> List_first = [1,4,7,9,33,22,55,77]>> List_first.sort (key=LambdaX: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=LambdaX:abs (x-10))>> [9, 7, 4, 1, 22, 33, 55, 77]#2. Custom Functions>>defwhich_closed (x):>>returnABS (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. Class emulation Function | __call__ ()>>classwhichclosed (object):>>def __init__(self,select_num):>> Self.select_num =Select_num>>def __call__(self,x):>>returnABS (xself.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__ () Action: Make an object callable interface>>classwhichclosed (object):>>def __init__(self,select_num):>> Self.select_num =Select_num>>def __call__(self,x):>>returnABS (xself.select_num)>> obj = whichclosed (10)#instantiating an object>> obj (2)#when the object is enclosed in parentheses, the __call__ () method is called inside the object;>> 8

Sort () method | Sorted () function | __call__ () method | Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.