sort
function is a very useful function that can sort the elements in a list. By default, sort
the function sorts the elements in ascending order, but sometimes we need a custom sorting of the list. In this case, we can key
implement custom sorting using parameters and passing a custom sort function.
-
The sample code is as follows:
def custom_sort(value, sort_list=[2,3,1,6,5]): """ 按照指定的顺序对返回数据排序 """ custom_order = sort_list if value in custom_order: return custom_order.index(value) else: return len(custom_order) a = [6,5,4,3,2,1] a.sort(key=custom_sort) print(a)
-
In the sample code above, we defined a
custom_sort
function called to implement custom sorting. -
custom_sort
The function takes two parameters:value
andsort_list
.value
The parameters represent the values to be sorted, andsort_list
the parameters represent the specified sort order. Ifvalue
insort_list
,custom_sort
the function returns the indexvalue
insort_list
. Otherwise, the function will returnsort_list
the length. -
Python's custom sorting functions are very useful. It can sort the list according to its own needs instead of the default ascending or descending order, allowing for better management and processing of data.