Advanced function sorted () in Python

Source: Internet
Author: User

The python built-in sorted () function can sort the list:

>>>sorted ([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]

But sorted () is also a high-order function, which can receive a comparison function to implement a custom sort, the definition of the 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 ranked after 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:

def reversed_cmp (x, y):    if x > y:        return-1    if x < y:        return 1    return 0

In this way, call sorted () and pass in the reversed_cmp to achieve a reverse order:

>>> Sorted ([36, 21, 12, 9, 5], reversed_cmp) [[5, 9]

Sorted () can also sort strings, and strings are compared by default in ASCII size:

>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits ']) [' Credits ', ' Zoo ', ' about ', ' Bob ']

The ' Zoo ' was ranked before ' about ' because the ' Z ' ASCII code was smaller than ' a '.

Advanced function sorted () in 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.