Python Sort description
This article simply records the use of the built-in functions sort () and sorted () in Python, as well as their differences in Python2 and Python3.
Overview
The built-in function sort () and sorted () can all sort a list, except that sort sorts the list itself (sorts the list), does not return, and sorted returns the sorted list. As with the parameters of the two, the sort performed is stable.
>>> l = [2, 4, 6, 1, 3]>>> l.sort()>>> l[1, 2, 3, 4, 6]>>> l = [2, 4, 6, 1, 3]>>> sorted(l)[1, 2, 3, 4, 6]>>> l[2, 4, 6, 1, 3]
The sorted in Python3
In Python3, the sorted definition of the built-in method is:
sorted(iterable[, key][, reverse])
which
- Iterable represents the data to be sorted
- Key is a function that receives a parameter, that is, each item in Iterable, and returns the value that needs to be compared. The default is None, which is to compare the item itself.
- Reverse is a Boolean type and reverse is True when reverse sorting. The default is False.
Example:
>>> students = [(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10),]>>> sorted(students, key=lambda x : x[0])[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]>>> sorted(students, key=lambda x : x[2])[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]>>> sorted(students, key=lambda x : x[2], reverse=True)[(‘john‘, ‘A‘, 15), (‘jane‘, ‘B‘, 12), (‘dave‘, ‘B‘, 10)]>>>>>> d = {‘data1‘:3, ‘data2‘:1, ‘data3‘:2, ‘data4‘:4}>>> sorted(d.items(), key=lambda x : x[1])[(‘data2‘, 1), (‘data3‘, 2), (‘data1‘, 3), (‘data4‘, 4)]
The sorted in Python2
In Python2, the sorted definition of the built-in method is:
sorted(iterable[, cmp[, key[, reverse]]])
which
- Iterable represents the data to be sorted
- CMP is a function that receives two parameters, such as CMP (A, B), returns a negative value, 0, or positive value, representing a less than, equal to, greater than B, respectively
- Key is a function that receives a parameter, that is, each item in Iterable, and returns the value that needs to be compared. The default is None, which compares the item itself
- Reverse is a Boolean type and reverse is True when reverse sorting. Default is False
Example:
>>> sorted(students, cmp=lambda x,y : cmp(x[2], y[2]))[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
Summarize
Python3 with respect to Python2, the CMP parameters are removed, simplifying the use of functions. For the two values to compare, such as A and B, only the <
comparison result of the symbol is used.
Python Sort description