custom sort function Python's built-in sorted () function can sort the list:>>>sorted ([36, 5, 12, 9, 21])[5, 9, 12, 21, 36] but sorted () is also a higher-order function, which can receive a comparison function to implement a custom sort, the definition of a comparison function is to pass in two elements to be compared x, y, if X should be in front of y, return-1, if x should be at the back of Y, return 1. returns 0 if x and y are equal. So, if we're going to sort in reverse order, we just need to write a reversed_cmp function:defreversed_cmp (x, y):ifX >y:return-1ifX <y:return1return0 In this way, call sorted () and pass in the reversed_cmp to achieve a reverse order:>>> Sorted ([36, 5, 12, 9, 21], reversed_cmp) [36, 21, 12, 9, 5]sorted () can also sort strings, and strings are compared by default in ASCII size:>>> Sorted (['Bob',' About','Zoo',' Credit'])[' Credit','Zoo',' About','Bob']'Zoo'Row in' About'Before it was because'Z'The ASCII code ratio'a'when small tasks sort strings, it is sometimes more customary to ignore the case sort. Use the sorted () higher-order function to implement an algorithm that ignores case ordering. Input: ['Bob',' About','Zoo',' Credit'] Output: [' About','Bob',' Credit','Zoo']defcmp_ignore_case (S1, s2): T1=S1.lower (); T2=S2.lower (); if(t1>T2):return1if(t1==T2):return0return-1PrintSorted (['Bob',' About','Zoo',' Credit'], Cmp_ignore_case)
Python custom sort function