Python sequence (6) list sorting

Time:2020-11-20

 

1. Sort method sort original address sort

    list.sort(key=None,reverse=False(or True))

When reverse = false: it is a forward sort;

When reverse = true: reverse sort.

The default is false.

2. Key: sort keyword. The value is a function. This function has only one parameter and returns a value. For example, there is a list of user objects, which you want to pass through the user of the object_ The ID tree is used for sorting, which can provide a user instance as input and output corresponding user_ ID value is given to key (i.e. key = lambda U: Uuser_ ID or key = attrgetter (“user_ id’))

3. After execution, the original list will be changed. If you don’t need the original list, the efficiency is slightly higher

>>> list = [1,2,3,4,5,6,7,8,9]
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> import random>>>  random.shuffle (list)
>>> list
[8, 1, 9, 2, 4, 3, 5, 6, 7]
>>>  list.sort () ා the default is ascending sort
>>>  list.sort (reverse = true) ා descending sort
>>> list
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>  list.sort (key = lambda x: len (STR (x))) # sort by the length of the converted string
>>> list
[9, 8, 7, 6, 5, 4, 3, 2, 1]

4. Use the built-in function sorted to sort the list and return the new list

>>> list
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>>Sorted (list) ා ascending sort
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>Sorted (list, reverse = true) ා descending sort
[9, 8, 7, 6, 5, 4, 3, 2, 1]

5. Use the reverse method of the list object to reverse the elements in place

 

>>> list
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> list.reverse()
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]

6. Use the built-in function return method to do not arrange the list elements and return the iterated object

 

7. Use the reversed method of the list object to arrange the list elements in reverse order and return the iterated object