Detailed Explanation of the Usage of Python Sorting Function

  • 2021-08-21 20:57:48
  • OfStack

The Python sorting function perfectly embodies the simplicity of Python language. For List objects, we can directly call the sort () function (which is more appropriately called "method" here) to sort, while for other iterative objects (such as set and dict), we can use the more flexible sorted () function.

1. sort () function of List

The Python source code builtins. py file defines the sort () function as follows


 def sort(self, key=None, reverse=False):
 """ L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* """
 pass

As you can see, the sort () function has no return value and has two parameters. key represents the function of arrangement basis; reverse refers to whether to reverse the list. By default, False indicates ascending order, and if it is set to True, it indicates descending order.

sort () is used as follows


L = [1, 2, 7, 4, 3]
L.sort()
print(L)
#[1, 2, 3, 4, 7]

Let's add one parameter to look at it, such as descending sorting:


L = [1, 2, 7, 4, 3]
L.sort(reverse=True)
print(L)
#[7, 4, 3, 2, 1]

For another example, we want to use key to achieve descending sorting. Here, we use the anonymous function lambda:


L = [1, 2, 7, 4, 3]
L.sort(key=lambda x : x*(-1))
print(L)
#[7, 4, 3, 2, 1]

Of course, there are many uses for key. We can set it as a built-in function or a custom function, such as an absolute value function:


L = [-1, 2, -7, 4, 3]
L.sort(key=abs)
print(L)
#[-1, 2, 3, 4, -7]

Python3 has another support for key, that is, the traditional cmp function is converted into key through cmp_to_key function of functools module. This is similar to the use of the lambda function, but in cases where the logic of comparison is more complex, it is clearer and easier to maintain.


from functools import cmp_to_key
L = [-1, 2, -7, 4, 3]
def cmp(a,b):
 if abs(a) < abs(b):
 return -1
 else:
 return 1
L.sort(key=cmp_to_key(cmp))
print(L)

2.sorted()

The sorted function is more versatile than the sort () function, which can only sort lists. Official documents have detailed instructions on it:


sorted(iterable, *, key=None, reverse=False)
Return a new sorted list from the items in iterable.

The return value of sorted () is of type List. The parameter list iterable represents an iterable object; * indicates that the position parameter ends here, and the following parameters must be specified with keywords; The usage of key and reverse parameters is identical to that of sort ().

sorted () is used as follows:


L = [1, 2, 7, 4, 3]
L1 = sorted(L)
print(L1)
#[1, 2, 3, 4, 7]

The usage of reverse and key is not shown separately, but can be referred to sort (). If the object we want to sort is a collection, then the usage is similar to list sorting 1:


S = {1, 2, 7, 4, 3}
S1= sorted(S)
print(S1)
#[1, 2, 3, 4, 7]

Note that this sort object is an set object, and the result is a list object (set object has no order 1). What if we want to achieve a complex 1-point sorting? For example, sorting dictionaries is based on key values, and the sorting result is a list composed of key-value pairs:


Dict = {'a':2, 'b':3, 'c':7, 'd':4, 'e':1}
L = sorted(Dict.items(), key=lambda x : x[1])
print(L)
#[('e', 1), ('a', 2), ('b', 3), ('d', 4), ('c', 7)]

Finally, give a question on Leetcode (sorted according to the frequency of characters):

Given 1 string, arrange the characters in the string in descending order of frequency.
Enter:
"tree"
Output:
"eert"
Explanation:
'e' appears twice, while 'r' and 't' appear only once. Therefore 'e' must precede 'r' and 't'. In addition, "eetr" is also an effective answer.

By using the sorted function code, it is clear and easy to read:


L = [1, 2, 7, 4, 3]
L.sort()
print(L)
#[1, 2, 3, 4, 7]
0

Note that d. keys () here generates an iterable object consisting of key, whereas Dict. items () in the previous code generates an iterable object consisting of a key-value pair object (this is an Tuple object).


Related articles: