Python sort, sorted

Source: Internet
Author: User

1.

(1) the. Sorted () method returns a new list (the default ascending order).

List.sort ()

(2). Another difference: the List.sort () method is defined only in the list, and the sorted () method is valid for all iteration sequences.

2.key Parameters/Functions

Starting with python2.4, the key parameter is added in List.sort () and sorted (), and the key is called at a lighter of each element.

For example, use the function specified by key to ignore the case of the string:

The sequence of complex objects is sorted by certain values of complex objects:

To sort complex objects that have named properties:

3.Operator module functions

The operator module has itemgetter, Attrgetter, which increases the Methodcaller method starting from 2.6.

operator allow multilevel sorting: first with grade, then by age

4. Ascending and Descending

Both List.sort () and sorted () accept a parameter of reverse (True or False) to indicate ascending or descending order.

5. Stability and complexity of sequencing

When multiple elements have the same key, their order of precedence is unchanged before and after sorting.

Note: The order of the "blue" after sorting is maintained, i.e. (' Blue ', 1) in front of (' Blue ', 2).

Build multiple steps for a more complex sort: Student data is sorted first in descending order of grade and then in ascending order of age

Python sort, sorted

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.