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 BasicsA 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.sort () method of the list. 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 ', ten),]
>>> Sorted (student_objects, Key=lambda student:student.age) # Sort by age [(' Dave ', ' B ', ten), (' Jane ', ' B ') , (' John ', ' A ', ')]
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:
>>> from operator import Itemgetter, Attrgetter
>>> Sorted (Student_tuples, Key=itemgetter (2)) [(' Dave ', ' B ', ten), (' Jane ', ' B ', '), (' John ', ' A ', 15)]
>>> Sorted (student_objects, Key=attrgetter (' age ')) [(' Dave ', ' B ', ten), (' Jane ', ' B ', '), (' John ', ' A ', 15)]
The operator module supports multilevel sequencing. For example, sort by score first, then by age:
>>> Sorted (Student_tuples, Key=itemgetter) [(' John ', ' A ', '), (' Dave ', ' B ', ten), (' Jane ', ' B ', 12)]
>>> Sorted (student_objects, Key=attrgetter (' Grade ', ' age ')) [(' John ', ' A ', '), (' Dave ', ' B ', ten), (' Jane ', ' B ', 12)]
4) Ascending and descending
Both List.sort () and sorted () receive a reverse parameter. It is a flag used for descending sorting. For example, to get a descending sort of student age:
>>> Sorted (Student_tuples, Key=itemgetter (2), reverse=true) [(' John ', ' A ', '), (' Jane ', ' B ', '), (' Dave ', ' B ', )] >>> sorted (student_objects, Key=attrgetter (' age '), reverse=true) [(' John ', ' A ', '), (' Jane ', ' B ', 12 ), (' Dave ', ' B ', 10)]
5) Sort stability and complex sequencing starting with Python2.2, the ordering is guaranteed to be stable. This means that when multiple records have the same keywords, their original sort is retained.
>>> sorted (data, Key=itemgetter (0)) [(' Blue ', 1), (' Blue ', 2), (' Red ', 1), (' Red ', 2)]
Notice that two ' blue ' records retain their original order, so (' Blue ', 1) is guaranteed before (' Blue ', 2). This good feature allows you to create a complex sort. For example, the student record is sorted in descending order of merit, in ascending order of two in the year. Sort by age first and then by score.
>>> s=sorted (Student_object,key=attrgettter (' Age ')) # Sort on secondary key
>>> Sorted (S,key=attrgetter (' Grade '), reverse=true) [(' Dave ', ' B ', ten), (' Jane ', ' B ', '), (' John ', ' A ', 15)]
How to use the sorted () method in Python