#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