The List.sort function of Python3

Source: Internet
Author: User

Sort (*, Key=none, Reverse=none)

Key denotes the sort keyword, and the reserve indicates whether it is in reverse order.

The Python3 sort is a stable order.

1. Simple numeric sorting

A = [5,3,2,4,1]
print (a)
a.sort ()
print (a)

2. Simple string sorting

A = [' abc ', ' ACB ', ' AAC ', ' abc ']
print (a)
a.sort ()
print (a)

3. The ordering of the element list

A = [[1,2],[2,1],[1,1],[2,2]]
print (a)
a.sort ()
print (a)

4. Sorting of custom comparison methods

such as the first element in reverse order, the second element positive sequence

Here you use the lambda function. A lambda function is a temporary function, a bit like the C-language macro definition or the inline in C + +, and the parameter must only be a pass value.

The parameters here refer to an element in the list.

a = [[[1,2],[2,1],[1,1],[2,2]]
print (a)
A.sort (Key=lambda x: (-x[0],x[1))
print (a)




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.