Consider the following scenario :
list Object's sort() The first parameter of the method key The required function has only one input parameter , If we want to have multiple input parameters , What shall I do? ?
We can make use of Python Nested definitions of functions .
Sample code first , Then explain .
The sample code is as follows :
def sort_priority(p_list, group):
def helper(x):
if x in group:
return [0, x]
else:
return [1, x]
p_list.sort(key=helper)
list1 = [1, 5, 3, 9, 7, 4, 2, 8, 6]
group1 = [7, 9]
sort_priority(list1, group1)
The operation results are as follows :
The above code defines a function sort_priority(), Its function is to list p_list Sort , When sorting group The elements in the top row .
How to achieve it ?
Mainly to make use of list Object's sort() The first parameter of the method key Realization . For a detailed description of this parameter, see the blog https://blog.csdn.net/wenhao_ir/article/details/125406092
This parameter key The called function can only have one parameter , So we need to be in the function sort_priority() And then define a function nested inside helper(), function helper() There is only one input parameter for , Is a list of p_list Every element of .
With this function helper(), So we can do this in the function sort_priority() Call in list Object's sort() The method , So the sentence
p_list.sort(key=helper)
And the function helper() Is under the same indent level .
function helper() Actually on the list p_list Each element in is classified , That is, if the element value is 7 or 9, Then return to the list [0,7] or [0,9], If the element value is not 7 or 9, Then return to the list [0,x]. In the end, it is equivalent to sorting the following list elements :
[1,1]
[1,5]
[1,3]
[0,9]
[0,7]
[1,4]
[1,2]
[1,8]
[1,6]
Combined with the blog :
https://blog.csdn.net/wenhao_ir/article/details/125406092
The method of sorting list elements in , That is, the first row of the list elements 0 Elements , And then arrange the... In each list element 1 Rules for elements , The list elements above will be arranged in the following order :
[0,7]
[0,9]
[1,1]
[1,2]
[1,3]
[1,4]
[1,5]
[1,6]
[1,8]
So, of the items to be sorted list1 The final order is :
[7, 9, 1, 2, 3, 4, 5, 6, 8]
summary : adopt Python Function nesting definition , combining list Object's sort() Method , We implemented list sorting with additional parameters .