Python Learning note __4.1.3 sorted

Source: Internet
Author: User
Tags sorted by name

# This is a learning note for the Liaoche teacher Python tutorial

1 , overview

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

The sorted () function is also a high-order function that can receive a key function to implement a custom sort, and the function specified by key will be applied to each element of the list and sorted according to the result returned by the key function.

# Direct Sort

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

[-21,-12, 5, 9, 36]

# Accept the key function sort

>>> sorted ([5, -12, 9, -21], key=abs)

[5, 9,-12,-21, 36]

# Sort by alphabetical order

>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], Key=str.lower) # sorted by default is ASCII sorted, and z>a, so need to add key function

[' About ', ' Bob ', ' credits ', ' Zoo ']

2 , examples

1,Suppose we use a group of tuples to represent student names and scores:L = [(' Bob ', the), (' Adam ', the), (' Bart ', the), (' Lisa ', the)]

Please use Sorted () The above list is sorted by name, respectively:

#-*-Coding:utf-8-*-

L = [(' Bob ', ', '), (' Adam ', ' the '), (' Bart ', ' the '), (' Lisa ', 88)]

# Sort by name

def by_name (t):

return t[0]

# Sort by score. -t[1], the higher thescore, the smaller the minus sign, the more forward

def by_score (t):

RETURN-T[1]

# Test

L2 = sorted (L, Key=by_name)
Print (L2)

# Sort by name

[(' Adam ', the "," (' Bart '), (' Bob ', '), (' Lisa ', 88)]

# Sort by score

[(' Adam ', "the"), (' Lisa ', ","), (' Bob ', '), (' Bart ', 66)]


Python Learning note __4.1.3 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.