functiontools模块

#!/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)是一个k类
# 当x=4,y=3的时候,k类被实例化,mycamp是lambda x,y:x-y return x-y
# 首先当进行sort比较的时候,列表里面的元素被实例化传进去
# self.obj = 4 other.obj = 3
# sort函数默认是从小到大排列,在比较的过程中,由于4比3大,自动触发__gt__这个函数,
# mycmp的返回值是4 -3 = 1,再和0做比较,1 > 0,所以cmp_to_key(mycmp)的返回值为True
# 所以正序排列
# 如果mycamp是lambda x,y:x-y return y-x
# self.obj = 4 other.obj = 3
# sort函数默认是从小到大排列,在比较的过程中,由于4比3大,自动触发__gt__这个函数,
# mycmp的返回值是3 - 4 = -1,再和0做比较,-1 < 0,所以cmp_to_key(mycmp)的返回值为False
# 所以反序排列
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
posted @ 2017-02-20 09:25  梁伟雄的博客  阅读(1609)  评论(0编辑  收藏  举报