Python High-order function--Sorted

Source: Internet
Author: User

For details, please refer to the official website of Liao Xuefeng, here are just a few excerpts, experience and practice of coding.

  1. Python's built-in sorted() functions can sort the list:

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

  2. sorted()A function is also a higher-order function, and it can also receive a key function to implement a custom sort, for example, by absolute size:
    >>> sorted ([5, -12, 9, -21], key=ABS) [5, 9,-12,-21, 36]

  3. It is important to emphasize that sorted will only pass the elements of the first parameter list into the function specified by the key, not the entire list.
  4. To reverse order, you do not have to change the key function, you can pass in the third argumentreverse=True
    >>> Sorted (['Bob',' About','Zoo',' Credit'], Key=str.lower, reverse=True) ['Zoo',' Credit','Bob',' About']
  5. sorted()the key to sorting is to implement a mapping function.
  6. Practice
    1. Suppose we use a group of tuples to represent student names and scores:
      L = [(‘Bob‘, 75), (‘Adam‘, 92), (‘Bart‘, 66), (‘Lisa‘, 88)]

      Please sorted() sort the above list by name:

      # -*-coding:utf-8-*- L = [('Bob', '), ('Adam', "), ('Bart') ('Lisa', ")]def  by_name (t):     return  = sorted (L, key=by_name)print(L2)

    2. Then sort by grades from highest to lowest:
      # -*-coding:utf-8-*- L = [('Bob', '), ('Adam', "), ('Bart') ('Lisa', ")]def  By_score (t):     return t[1= sorted (L, key=by_score)print(L2)

Python High-order function--Sorted

Related Article

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.