How to use the sorted () method in Python

Source: Internet
Author: User
Tags iterable

How to use the sorted () method in Python

Python Font size <span pnt= "" fc03 "=" "id=" $_blog_subscribe "style=" margin:0px; padding:0px; " > Subscription

1. First say iterable, Chinese meaning is an iterator. The explanation for iterable in Python's help document is that Iteralbe refers to an object that can return one of its members at once. Iterable mainly consists of 3 categories:The first class is all sequence types, such as List, str (string), tuple (tuple). The second class is some non-sequential types, such as Dict (dictionary), file (files). The third class is any object that you define that contains the class of the __iter__ () or __getitem__ () method.
explanation of the sorted method in the 2.Python Help documentation: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 that receives a parameter, 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. 3. The specific usage is as follows: 1) sort the base a simple ascending arrangement is simple-just call the sorted () function. This function returns a new sorted list. :>>> sorted ([5,2,3,1,4]) [1,2,3,4,5] You can also use the list's List.sort () method. This method modifies the original list (the return value is None). Usually this method is less convenient than sorted ()-If you do not need the original List,list.sort () method, the efficiency will be slightly higher. >>> a=[5,2,3,1,4]>>> a.sort () >>> a[1,2,3,4,5] Another difference is that the List.sort () method is defined only for list. The sorted () function can receive any iterable.
>>> Sorted ({1: ' D ', 2: ' B ', 3: ' B ', 4: ' E ', 5: ' A '}) [1, 2, 3, 4, 5]
2) key Functions (keyword function)
Starting with Python2.4, the List.sort () and sorted () methods all add a key parameter to illustrate a function that calls each element in the list before it is compared.
For example, here is a case insensitive string comparison:
>>> sorted ("This was a test string from Andrew". Split (), key=str.lower) [' A ', ' Andrew ', ' from ', ' is ', ' string ', ' t Est ', ' this ']
The value of key should be a function that takes a parameter and returns a keyword for comparison. This technique is faster because the function is only called once for each input record.
A comparison of complex objects is usually the use of the object's slices as a keyword. For example:
>>> student_tuples = [         (' John ', ' A ', '),         (' Jane ', ' B ', '),         (' Dave ', ' B ', 10),]
>>> Sorted (student_tuples, Key=lambda student:student[2]) # Sort by age [(' Dave ', ' B ', ten), (' Jane ', ' B ', 12 ), (' John ', ' A ', 15)]
The same technique applies to objects that have named properties. For example:
>>> class Student:def __init__ (self, name, grade, age):
Self.name = Name
Self.grade = Grade
Self.age = Age
def __repr__ (self):
Return Repr ((Self.name, Self.grade, Self.age))
>>> student_objects = [Student (' John ', ' A ', '), Student (' Jane ', ' B ', '), student (' Dave ', ' B ', 10),]
>>> Sorted (student_objects, Key=lambda student:student.age) # Sort by age [(' Dave ', ' B ', ten), (' Jane ', ' B ', 12 ), (' John ', ' A ', 15)]
3) Operator Module Functions (function in Operator module)
The key-function pattern above is common, so Python provides convenient functions to make ancestral functions simpler and faster. The operator module has itemgetter,attrgetter, as well as the Methodcaller function starting from Python2.6.
Using these functions, the above example becomes simpler and faster:

How to use the sorted () method in Python

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.