Python learns how to sort list items

  • 2020-06-01 10:13:09
  • OfStack

This article introduces the content related to the sorting of Python list items, which is Shared for your reference and learning. Let's take a look at the detailed introduction below:

Typical code 1:


data_list = [6, 9, 1, 3, 0, 10, 100, -100] 
data_list.sort() 
print(data_list) 

Output 1:


[-100, 0, 1, 3, 6, 9, 10, 100] 

Typical code 2:


data_list = [6, 9, 1, 3, 0, 10, 100, -100] 
data_list_copy = sorted(data_list) 
print(data_list) 
print(data_list_copy) 

Output 2:


[6, 9, 1, 3, 0, 10, 100, -100] 
[-100, 0, 1, 3, 6, 9, 10, 100] 

Application scenarios

When you need to sort items in a list. Typical code 1 is a sorting method sort of the list itself, which is automatically sorted in ascending order and in situ, and the sorted list itself will be modified. Typical code 2 is the call to the built-in function sort, which generates a new sorted list object, with the original list unaffected. Both of these methods accept almost the same parameter as 1. They both accept an key parameter, which is used to specify which part of the object to use for sorting:


data_list = [(0, 100), (77, 34), (55, 97)] 
data_list.sort(key=lambda x: x[1]) #  We want number one based on the list item 2 Number sort  
print(data_list) 
 
>>> [(77, 34), (55, 97), (0, 100)] 

Another frequently used parameter is reverse, which specifies whether to sort in reverse order. The default is False:


data_list = [(0, 100), (77, 34), (55, 97)] 
data_list.sort(key=lambda x: x[1], reverse=True) #  We want number one based on the list item 2 The Numbers are sorted and in reverse order  
print(data_list) 
>>> [(0, 100), (55, 97), (77, 34)] 

The benefits

1. Built-in sorting method, high execution efficiency, strong expression, make the code more compact, has been read

2. Flexible parameter for specifying the sort benchmark, much more convenient than having to write an comparator in a language like Java

Other instructions

1. The sorted built-in function is more widely applicable than the sort method of lists, which can sort iterable data structures other than lists;

2. list built-in sort method, which belongs to in-situ sorting, can theoretically save memory consumption;

conclusion


Related articles: