A method instance analysis of Python ordering list

Source: Internet
Author: User
The example in this article describes how Python sorts the list. Share to everyone for your reference. The specific analysis is as follows:

1. Sort () function

The sort () function sorts the list using a fixed sorting algorithm. The sort () function changes the original list when the list is sorted, allowing the elements to be arranged in a certain order, rather than simply returning a sorted copy of the list.

Note that the sort () function changes the original list, and the function return value is null or none. Therefore, it is not straightforward to use the sort () function directly if you need an ordered list copy and keep the original list intact. To do this, use sort () to get the copy y of the list x first, and then sort the Y. The code is as follows:

X=[4,6,2,1,7,9,4]y=x[:]y.sort () Print xprint y

The results are as follows:

[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]

Description: Call x[:] Gets a shard that contains all the elements of X, which is a very efficient way to replicate the entire list. It is no use using y=x to simply copy X to Y, because doing so allows both X and Y to point to the same list.

2. Sorted () function

Another way to get a sorted copy of a list is to use the sorted () function. Note that the sorted () function can be used for any object that can be iterated.

x=[4,6,2,1,7,9,4]y=sorted (x) print xprint y

Results:

[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]

Hopefully this article will help you with Python programming.

  • 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.