Application of sorted () function in Python

Source: Internet
Author: User

1. Application of sorted () function

    • The sorted () function can accept a parameter
    • The sorted () function can also accept a key function to implement a custom sort.
    • Sorted () can also accept the third parameter: reverse=true for reverse ordering
  • An example of accepting a parameter is as follows:
    Sorted ([5,-3,1]) ——————-> results [ -3,1,5] Sort by size
  • Accepts two parameters: in addition to receiving the data to be sorted, you can also receive a function to sort the requirements of this function, for example: sorted ([5,-3,1],key=abs) ———— –> result: [1,-3,5]

Exercises: d=[(' Wu ', 98), (' Rang ', ","), (' Hao ', 76)] sorted by name and score respectively

The code is as follows:

#coding: UTF-8 def my_name(t):    returnt[0] def my_score(t):    returnt[1]#测试d=[(' Wu ',98),(' rang ', the),(' Hao ', the)]#按名字进行排序l1=sorted (d,key=my_name) print ("By_name sorted:", L1) l2=sorted (d,key=my_score) print ("By_score sorted", L2)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Application of sorted () function 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.