Understanding of sorted functions in Python (sort list lists, sort dict dictionaries)

Source: Internet
Author: User
Tags iterable

In the Python manual:

Sorted (Iterable[,cmp,[,key[,reverse=true]])

Function: Return a new sorted list from the items in iterable.

The first parameter is a iterable, and the return value is a list that sorts the elements in iterable. The optional parameters are three, CMP, key, and reverse. 1) CMP Specifies a custom comparison function that receives two parameters (elements of iterable), returns a negative number if the first argument is less than the second argument, returns 0 if the first argument is equal to the second argument, or returns a positive number if the first argument is greater than the second argument. The default value is None. 2) key specifies a function to receive iterable, which is used to extract a keyword from each element for comparison. The default value is None. 3) Reverse is a Boolean value. If set to True, list elements are sorted in reverse order. In general, key and reverse are faster than an equivalent CMP function. This is because the CMP is called multiple times for each list element, and key and reverse are called only once.
#coding =utf-8
#例子
Items = [ {'name':'John Doe',' Age': 40}, {'name':'Zhang San',' Age': 30}, {'name':'Harry',' Age': 50},]
#对items字典按照年龄排序
Items1 = sorted (items,key=lambda i:i[' age ')

#其中 Lambda understands that lambda is an expression, I is a loop variable, and the range is the same as the above example
Def Paixu ():
For I in Itemes:
I[' age ']
Print i[' age ']

items1 = sorted (Items,key=paixu ())

Python sorted () function

How to use the sorted () method in Python

Understanding of sorted functions in Python (sort list lists, sort dict dictionaries)

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.