Python sorting introduction and python sorting
Python sorting
This article briefly records the usage of the built-in functions sort () and sorted () in Python, and their differences in Python2 and Python3.
Overview
Both the built-in functions sort () and sorted () can sort a List. the difference between them is that sort sorts the List itself (sorts the list in place) without returning, sorted returns the sorted list. Like the two parameters, the sorting 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]
Sorted in Python3
In Python3, the built-in method sorted is defined:
sorted(iterable[, key][, reverse])
Where
- Iterable indicates the data to be sorted
- Key is a function that receives a parameter, that is, each item in the iterable, and returns the value to be compared. The default value is None, indicating that the item itself is compared.
- The reverse type is Boolean, and the reverse sorting is performed when the reverse is True. The default value 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)]
Sorted in Python2
In Python2, the built-in method sorted is defined:
sorted(iterable[, cmp[, key[, reverse]]])
Where
- Iterable indicates the data to be sorted
- Cmp is a function that receives two parameters, such as cmp (a, B) and returns a negative value, 0, or positive value, representing a less than, equal to, or greater than B.
- Key is a function that receives a parameter, that is, each item in the iterable, and returns the value to be compared. The default value is None, indicating that the item itself is compared.
- The reverse type is Boolean, and the reverse sorting is performed when the reverse is True. The default value is False.
Example:
>>> sorted(students, cmp=lambda x,y : cmp(x[2], y[2]))[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Summary
Compared with Python2, Python3 removes the cmp parameter and simplifies the use of functions. For the two values to be compared, such as a and B, only use<Symbol comparison result.