Python的cmp_to_key函数如何工作? [英] How does Python's cmp_to_key function work?

查看:459
本文介绍了Python的cmp_to_key函数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在此处遇到了此功能。

我对如何实现感到困惑- cmp_to_key key 函数如何c $ c>知道给定元素应该位于什么位置,而无需检查给定元素与感兴趣的其他元素的比较情况?

I am baffled as to how this would be implemented -- how does the key function generated by cmp_to_key know what "position" a given element should be without checking how the given element compares with every other element of interest?

推荐答案

cmp_to_key 方法返回一个用作代理键的特殊对象:

The cmp_to_key method returns a special object that acts as a surrogate key:

class K(object):
    __slots__ = ['obj']
    def __init__(self, obj, *args):
        self.obj = obj
    def __lt__(self, other):
        return mycmp(self.obj, other.obj) < 0
    def __gt__(self, other):
        return mycmp(self.obj, other.obj) > 0
    def __eq__(self, other):
        return mycmp(self.obj, other.obj) == 0
    def __le__(self, other):
        return mycmp(self.obj, other.obj) <= 0
    def __ge__(self, other):
        return mycmp(self.obj, other.obj) >= 0
    def __ne__(self, other):
        return mycmp(self.obj, other.obj) != 0
    def __hash__(self):
        raise TypeError('hash not implemented')

排序时,每个键都将与序列中的其他大多数键进行比较。在位置0的这个元素是否小于或大于另一个对象?

When sorting, each key will get compared to most other keys in the sequence. Is this element at position 0 lower than or greater than that other object?

无论何时发生,都会调用特殊的方法挂钩,因此 __ lt __ __ gt __ 会被调用,替代键会变成对 cmp 方法的调用。

Whenever that happens, the special method hooks are invoked, so __lt__ or __gt__ is called, which the surrogate key turns into a call to the cmp method instead.

因此列表 [1、2、3] 排序为 [K (1),K(2),K(3)] ,如果将 K(1) K(2)来查看 K(1)是否较低,然后是 K(1)。__lt__ (K(2))被调用,它被转换为 mycmp(1,2)< 0

So the list [1, 2, 3] is sorted as [K(1), K(2), K(3)], and if, say, K(1) is compared with K(2) to see if K(1) is lower, then K(1).__lt__(K(2)) is called, which is translated to mycmp(1, 2) < 0.

这就是旧的 cmp 方法的工作方式 ;根据第一个参数是否小于,等于或大于第二个参数,返回-1、0或1。代理键将这些数字转换为比较运算符的布尔值。

This is how the old cmp method was working anyway; return -1, 0 or 1 depending on wether the first argument is lower than, equal to or greater than the second argument. The surrogate key translates those numbers back to boolean values for the comparison operators.

代理键一点都不需要了解有关绝对位置。它只需要知道要与之比较的另一个对象,并且特殊的方法挂钩提供了另一个对象。

At no point does the surrogate key need to know anything about absolute positions. It only needs to know about one other object it is being compared with, and the special method hooks provide that other object.

这篇关于Python的cmp_to_key函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆