Home > Article > Backend Development > Python learning tips: Sample code sharing for sorting list items
This article mainly introduces to you the relevant information on sorting list items of Python learning tips. The introduction in the article is very detailed. Friends who need it can refer to it. Let’s learn with the editor. Study it.
This article introduces the relevant content about the sorting of Python list items. It is shared for everyone’s reference and learning. Let’s take a look at the detailed introduction:
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 scenario
Used when items in the list need to be sorted. Among them, the typical code 1 is a sorting method of the list itself, which is automatically sorted in ascending order and sorted in place. The sorted list itself will be modified; the typical code 2 is the built-in function## that is called. #sort will generate a new sorted list object , and the original list will not be affected. The parameters accepted by these two methods are almost the same. They both accept a key parameter. This parameter is used to specify which part of the object is used as the basis for sorting:
data_list = [(0, 100), (77, 34), (55, 97)] data_list.sort(key=lambda x: x[1]) # 我们想要基于列表项的第二个数进行排序 print(data_list) >>> [(77, 34), (55, 97), (0, 100)]Another common The parameter used is reverse, which is used to specify 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) # 我们想要基于列表项的第二个数进行排序,并倒序 print(data_list) >>> [(0, 100), (55, 97), (77, 34)]
Benefits
OthersExplanation
1. The sorted built-in function is more suitable than the sort method of the list It has a wider scope and can sort iterable data structures other than lists; 2. The built-in sort method of list is in-place sorting, which can theoretically save memory consumption;Summarize
The above is the detailed content of Python learning tips: Sample code sharing for sorting list items. For more information, please follow other related articles on the PHP Chinese website!