The difference between sort() function and sorted() function

-----------sort() can only be used on the list list, that is, list = ['zhang','qian','sun']. And the sort function has only two parameters, namely key and reverse. Reverse defaults to False (positive order), and key can specify a method with only one parameter

Note that sort() and reverse() are two methods of lists, and sorted() is a function

The corresponding format is: list.sort() or list.reverse(), but x = list.sort() will report an error

-----------sorted() function: There are three parameters: iterable, key, reverse

# All objects that can be iterated can be sorted by sorted, and sorting will not change the original object, so it is *    

The format is parameter = sorted(iterable, *, key=None, reverse = False)

Where sorted(d.items(), key = lambda x: x[1]) d.items() is the object to be sorted

    Key = lambda variable: variable [dimension], the dimension can be set according to your needs (for example, the dimension is represented by a string, as shown in the example in Figure 1)

1. The sorting of the dictionary and the dictionary, as shown in the figure below:

       

2. The sorting of tuples and tuples is shown in the following figure:

 3. Through the code, simply explain the difference between sort() and sorted(), as shown in the following figure:

                        

 4. The operator.itemgetter function. The itemgetter function of the operator module: Get the data of which dimensions of the object, and the parameter is the serial number (that is, the serial number of the data to be obtained in the object), so that multiple elements can be sorted at the same time, as shown in the following figure:

                                                                   

 

Guess you like

Origin blog.csdn.net/xielang13/article/details/108804548