Home » Python » Python custom sorting function

Python custom sorting function


python custom sorting functions, there are two ways,


's first custom function:



The order function of
# custom
Def func (x, y):
If xReturn -1
If x==y:
Return 0
Else:
Return 1
A = [3,6,2,8,4]
Print u' positive sequence arrangement: ' sorted (a, func)
Print u' reverse order: ' (a, sorted, func, reverse=True) #reverse=True is the reversed sequence
# note that sorted requires second parameters is a function, so write func, instead of func (x, y),
#func (x, y) is the result of a value. Func is a function, following the use of lambda is also a function of 





Result:


 positive sequence: [2, 3, 4, 6, 8]
Reverse order: [8, 6, 4, 3, second 2]
lambda use anonymous functions and CMP function:


(CMP (x, y), if xy returns 1)


# uses lambda expressions
Print u' sorted: ' positive sequence (a, lambda, x, y:cmp (x, y)) # positive sequence
Print u' ' sorted; reverse order: (a, lambda, x, y:-cmp (x, y)) # reverse order
results:


 positive sequence: [2, 3, 4, 6, 8]
Reverse order: [8, 6, 4, 3, 2]










Latest