如何为降序值编写Python排序键函数

如何为降序值编写Python排序键函数,第1张

如何为降序值编写Python排序键函数

缓慢但优雅的方法是创建一个具有相反顺序的值包装器:

from functools import total_ordering@total_orderingclass ReversedOrder:    def __init__(self, value):        self.value = value    def __eq__(self, other):        return other.value == self.value    def __lt__(self, other):        return other.value < self.value

如果没有

functools.total_ordering
,则必须实施所有6个比较,例如:

import operatorclass ReversedOrder:    def __init__(self, value):        self.value = valuefor x in ['__lt__', '__le__', '__eq__', '__ne__', '__ge__', '__gt__']:    op = getattr(operator, x)    setattr(ReversedOrder, x, lambda self, other, op=op: op(other.value, self.value))


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5646689.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存