Python sort, for list, dictionary

Source: Internet
Author: User

Python's internal container, probably divided into: tuple,set,list,dict, in order to sort, the list and Dictionary of the Order of more requirements, tuple mainly as an immutable container, set to repeat, the following list and dict common sorting methods summarized:

First, List

1, list sorting is very simple, mainly see the list of elements, if the element is composed of single values, such as the following method:

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

The list itself comes with the sort () method, which operates on the list itself, which means that the original structure of a is changed.

2. The list element is made up of tuples, which require a column of tuples to be sorted, as shown in the following example:

Using Python's built-in function, sorted (), obviously put the sorting results in the B list, but it doesn't actually change the original structure of the A data, if we still use the sort () method of the list? Examples are as follows:

There is one more way to do this, but use the CMP parameter:


CMP is a comparison, x[1],y[1] represents the second column of the first and second elements, reverse=0 means no inversion, can reverse=false, the same effect, of course, reverse can not write, the default is False

3. Using operator module

>>> a[(' C ', 1), (' B ', 2), (' A ', 3)]>>> B = Sorted (A,key=itemgetter (0)) >>> b[(' A ', 3), (' B ', 2), (' C ', 1)]

Second, the dictionary sort

Dictionary, the main thing is to sort by key or value.

There are ways to do it directly with a for loop, but I think direct sorted () is clear.

Summarize:

Generally do sort, list can be based on whether to change the original data structure to choose different methods, the dictionary with sorted can, about efficiency, in fact, I personally feel the key method with lambda faster.



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

Python sort, for list, dictionary

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.