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

The move in recent versions of Python to passing a key function to sort() from the previous cmp function is making it trickier for me to perform complex sorts on certain objects.

例如,我想用一组字符串平局决胜者字段对一组对象从最新到最旧进行排序。因此,我希望日期按相反顺序排列,但字符串按其自然顺序排列。使用比较功能,我可以将日期字段与字符串字段进行比较。但是,通过键功能,我需要找到某种方法来反转/反转日期或字符串。

处理数字很容易(虽然很丑)-只是从某些东西中减去它们-但是我是否必须找到类似的日期破解方法(从另一个日期中减去它们并比较timedelta?)和字符串(...我不知道如何以与语言环境无关的方式颠倒它们的顺序)。

I know of the existence of functools.cmp_to_key() but it is described as being "primarily used as a transition tool for programs being converted to Python 3 where comparison functions are no longer supported". This implies that I should be able to do what I want with the key method - but how?

最佳答案

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

from functools import total_ordering
@total_ordering
class 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

If you don't have functools.total_ordering, you'd have to implement all 6 comparisons, e.g.:

import operator
class ReversedOrder:
    def __init__(self, value):
        self.value = value
for 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))

    公众号
    关注公众号订阅更多技术干货!