Python Custom sort function

Source: Internet
Author: User

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

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.