Preface
In Python, there are many ways to sort, the most commonly used is to use the built-insort()
Methods andsorted()
Functions, next I will lead you to easily learn these two methods through various cases, and at the same time, I will extend some practical sorting case template code.
1. Use of sort() method
sort()
The method is a method of a List object. It will directly sort the original list without returning the new list. This means it changes the order of the original list, which can only work on the list.
1.1 Basic Operation
Syntax format:
List object.sort(reverse=False)
, sort ascending, no reverse parameter is written by default, and sorts in ascending order
List object.sort(reverse=True)
, sorted descendingly
Case 1: Sort the elements in the list ascending order
# All elements in the list are numeric typesmy_list = [5, 2, 9, 1, 5, 6] my_list.sort() # default ascending order sort,print(my_list) # Output: [1, 2, 5, 5, 6, 9] # All elements in the list are of string typewords = ["apple", "orange", "banana", "pear"] () print(words) # Output: ['apple', 'banana', 'orange', 'pear']
Case 2: Sort elements in a list in descending order
# All elements in the list are numeric typesmy_list = [5, 2, 9, 1, 5, 6] my_list.sort(reverse=True) # Sort in descending order, you can pass reverse=True parameterprint(my_list) # Output: [9, 6, 5, 5, 2, 1] # All elements in the list are of string typewords = ["apple", "orange", "banana", "pear"] (reverse=True) print(words) # Output: ['pear', 'orange', 'banana', 'apple']
Notice:
- The elements in the list must be of the same data type before they can be sorted, otherwise an error will be reported.
- The sort method can only act on the list object and cannot be followed directly by the data, otherwise None will be returned; such as:
# Incorrect usemy_list = [5, 2, 9, 1, 5, 6].sort() # The sort method cannot be directly followed by the dataprint(my_list) #Output: None # Use correctlymy_list = [5, 2, 9, 1, 5, 6] my_list.sort() # default ascending order sort,print(my_list) # Output: [1, 2, 5, 5, 6, 9]
- When the elements in the list are strings, the sort() method sorts according to the Unicode code points of the string. Specifically, the sort of strings is compared character by character:
1. Compare the first character of two strings and sort them according to their Unicode code point values.
2. If the first character is the same, compare the second character, and so on.
3. If all characters are the same, the two strings are considered equal.
1.2 Advanced operation (custom sorted objects)
Syntax format:List object.sort(reverse=,key=function name)
We passedkey
The parameter receives a function that is called on each element in the list, sorting the results returned by the function; the function can be an anonymous function, a custom function, or a built-in function.
Case 1: Sorting with built-in functions
# Sort by string length (applicable to string list)words = ["apple", "banana", "cherry", "date"] (key=len) # key followed by function nameprint(words) # Output: ['date', 'apple', 'banana', 'cherry']
Case 2: Sorting with anonymous functions
# Sort the list containing the tuple by the second elementtuple_list = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] tuple_list.sort(reverse=True,key=lambda x: x[1]) # Follow the anonymous function directly after the keyprint(tuple_list) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Case 3: Sort with custom functions
# Custom functionsdef custom(s): # Here s is used to receive elements in the list return len(s) # Return the length of each element in the list and sort by length words = ["apple", "banana", "cherry", "date"] (key=custom) print(words) # Output: ['date', 'apple', 'banana', 'cherry']
2. Use of sorted() function
sorted()
The function is a built-in function in Python. It will return a new sorted list without changing the original list. The sorted function is powerful and can sort all iterable objects, such as: strings, ancestors, etc., and return a sorted list.
2.1 Basic Operation
Syntax format:sorted(iterable object, reverse=)
Parameter description:
reverse=False
, sorted as ascending order, default not to be written as ascending order
reverse=True
, sorted descendingly
Case:
# Sort the list ascending ordermy_list = [5, 2, 9, 1, 5, 6] sorted_list = sorted(my_list) # Default ascending order sortprint(sorted_list) # Output: [1, 2, 5, 5, 6, 9]print(my_list) # Output: [5, 2, 9, 1, 5, 6], the original list has not been changed # If you want to sort in descending order, you can pass the reverse=True parametersorted_list_desc = sorted(my_list, reverse=True) print(sorted_list_desc) # Output: [9, 6, 5, 5, 2, 1] # Sort strings ascending orderstrs = '136297' new_strs = sorted(strs) print(new_strs) # Output: ['1', '2', '3', '6', '7', '9'], returns a sorted list
2.2 Operation is performed (custom sorted objects)
Syntax format:sorted (iterable object, reverse=, key=function name)
Whether it is the sort() method or the sorted() function, it can accept a key parameter to specify a function. This function will be called on each list element, and the sorting will be based on the returned result.
Case:
# Sort by string length (applicable to string list)words = ["apple", "banana", "cherry", "date"] sorted_words = sorted(words, key=len) # key followed by function nameprint(sorted_words) # Output: ['date', 'apple', 'banana', 'cherry'] # Sort the list containing the tuple by the second elementtuple_list = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] sorted_tuple_list = sorted(tuple_list, key=lambda x: x[1]) print(sorted_tuple_list) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Summarize:
- The sort method and sorted() function use the same operation, but the sort() method can only act on the list, while the sorted() method can act on all iterable objects.
- The sort() method is to sort on the original list object and will not generate a new list; and the sorted() function will generate a new list after sorting the iterable object.
3. Extension: sorting case template code
In our daily development, we often name some data, such as text, pictures, videos, audio, etc. in order, and store them in a folder. When we need to process these data through python, we usually get the path of each file and store it in a list. At this time, if we sort this list, some problems will arise, as follows:
Problem case:
image_paths = ['D:/image/','D:/image/','D:/image/','D:/image/','D:/image/', 'D:/image/','D:/image/','D:/image/','D:/image/','D:/image/', 'D:/image/'] image_paths.sort() # Sort ascendingprint(image_paths)
Output result:
['D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/']
illustrate:From the above results, we can see that we originally planned to sort the paths in ascending order in 1, 2, 3, 4..., but the result returned is not the case. The reason for this problem is that the sort() method and sorted() function sorted by the unicode code point value of each character when sorting the string. Therefore, we need to do some processing of the data and then sort it. Here we can use the key parameter to solve this problem.
Solution template code:
# Sort the elements in the list ascending orderimage_paths = ['D:/image/','D:/image/','D:/image/','D:/image/','D:/image/', 'D:/image/','D:/image/','D:/image/','D:/image/','D:/image/', 'D:/image/'] # Custom functionsdef sort_key(s): # Get the number part using slices and convert it into integers for sorting return int(''.join(filter(, s))) # 1. Use the soted() functionnew_image_paths = sorted(image_paths, key=sort_key) print(new_image_paths) # 2. Use the sort() methodimage_paths.sort(key=sort_key) print(image_paths) # The results returned by both methods are the same
Output result:
['D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/'] ['D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/', 'D:/image/']
Summarize
This is the article about the commonly used sorting operation sort method and sorted function use in Python. For more related contents of the python sorting sort method and sorted function usage, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!