Functiontools module, pythonfunctiontools
#! /Usr/bin/env python
#-*-Coding: UTF-8 -*-
From functools import cmp_to_key
A = [1, 6, 4, 5]
A. sort (key = cmp_to_key (lambda x, y: x-y ))
# Cmp_to_key (lambda x, y: x-y) is a k class
# When x = 4, y = 3, Class k is instantiated. mycamp is lambda x, y: x-y return x-y.
# First, when performing sort comparison, the elements in the list are instantiated and passed in.
# Self. obj = 4 other. obj = 3
# By default, the sort function is arranged from small to large. During the comparison process, the _ gt _ function is automatically triggered because it is larger than 4,
# The Return Value of mycmp is 4-3 = 1, and then compare it with 0. 1> 0. Therefore, the return value of cmp_to_key (mycmp) is True.
# So forward order
# If mycamp is lambda x, y: x-y return y-x
# Self. obj = 4 other. obj = 3
# By default, the sort function is arranged from small to large. During the comparison process, the _ gt _ function is automatically triggered because it is larger than 4,
# The Return Value of mycmp is 3-4 =-1, and then compare it with 0.-1 <0, so the return value of cmp_to_key (mycmp) is False.
# So sort in reverse order
Def cmp_to_key (mycmp ):
"Convert a cmp = function into a key = function """
Class K (object ):
_ Slots _ = ['obj ']
Def _ init _ (self, obj, * args ):
Self. obj = obj
Def _ gt _ (self, other ):
Return mycmp (self. obj, other. obj)> 0
Def _ gt _ (self, y): # real signature unknown; restored from _ doc __
"" X. _ gt _ (y) <=> x> y """
Pass
Return K