【问题标题】:Python overriding heapq comparison when using tuples使用元组时Python覆盖heapq比较
【发布时间】:2017-10-18 22:17:15
【问题描述】:

所以我知道在使用 heapq 模块创建基本上包含(键,值)对的堆时,您可以使用元组而不是直接值。

我还知道,您可以覆盖 heapq 模块的__lt__ 比较运算符,以便在创建和维护堆时进行自己的比较。

有没有办法覆盖这个运算符,以便比较元组的两个值?例如,如果第一个值与以下内容相等,我试图让 heapq 比较元组的第二个值:

def __lt__(self, other):
    return self[0] < other[0] if self[0] != other[0] else other[1] < self[1]

后半部分other[1] &lt; self[1] 是故意颠倒过来的,因为逻辑是第二个值较大的元组应该被认为是两者中较小的一个。

感谢您提前提供任何见解!

编辑:我想我对术语“重载”和“覆盖”之间的区别感到困惑。我指的是覆盖。

【问题讨论】:

    标签: python tuples comparison-operators


    【解决方案1】:

    是的,这会起作用。为了阐明在heapq 中使用自定义类的整个过程,以下是我编写的测试脚本的一些摘录,以尝试掌握asyncio。为了跟踪在不同时间关闭的计时器,我定义了这个类:

    class TimerTask :
        "actions to be invoked at specific times."
    
        def __init__(self, when, action) :
            self.when = when
            self.action = action
        #end __init__
    
        def __lt__(a, b) :
            return \
                a.when < b.when
        #end __lt__
    
    #end TimerTask
    

    这样的一行会将TimerTask 放在待处理队列中:

    heapq.heappush(self.pending, self.TimerTask(when, trigger_sleep_done))
    

    然后这个序列等待最早的挂起计时器到期并调用其相应的操作:

    try :
        until = self.pending[0].when
    except IndexError :
        # nothing more for event loop to do
        break
    #end try
    now = time.time()
    if until > now :
        time.sleep(until - now)
    #end if
    heapq.heappop(self.pending).action()
    

    【讨论】:

    • @Ellest 自定义类是实现特定重载运算符的最简单和最 Pythonic 的方式。您的方法可能行不通,因为def __lt__(self, other): 全局不会重载任何类的运算符。此外,不可能对内置类型进行修补。因此,虽然语法正确,但逻辑上不正确,最好的解决方案是自定义类。
    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 2021-09-13
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2015-08-01
    相关资源
    最近更新 更多