【问题标题】:How to write a custom comparator with custom sort in Python3 to use it in sorted() function如何在 Python3 中使用自定义排序编写自定义比较器以在 sorted() 函数中使用它
【发布时间】:2023-03-09 04:26:01
【问题描述】:

我目前遇到了编写比较器的问题。基本思想是编写一个函数,它接受参数(两个列表),但我想在这些列表的列表中使用它以在 sorted() 函数中使用它。我该怎么做?

比较器:

def dispersion_sort(frec, srec):

    if isinstance(frec, intervals.Interval) and isinstance(srec, intervals.Interval):
        if frec[DOUBLE_RES_COL] < srec[DOUBLE_RES_COL]:
            return frec
        if frec[DOUBLE_RES_COL] > srec[DOUBLE_RES_COL]:
            return srec
        if frec[DOUBLE_RES_COL].overlaps(srec[DOUBLE_RES_COL]):
            if (frec[DOUBLE_TIME_COL] < srec[DOUBLE_TIME_COL]):
                return frec
            else:
                return srec

    return frec

样本frec 数据: ['1', 'Mikhail Nitenko', '@login', '✅', [-0.000509228437634554,0.0007110924383354339], datetime.datetime(2020, 1, 2, 14, 46, 46)]

我想怎么称呼它:

results = sorted(results, key=dispersion_sort)

非常感谢!

【问题讨论】:

  • this 是您要找的吗?
  • 那么有什么问题,还提供一些示例数据和预期输出。另外,如果您使用自定义对象,请显示这些对象的定义

标签: python python-3.x sorting comparator


【解决方案1】:

您可以为此使用functools.cmp_to_key

from functools import cmp_to_key

results = sorted(results, key=cmp_to_key(dispersion_sort))

它将旧样式的比较器函数(带两个参数)转换为新样式的键函数(带一个参数)。

【讨论】:

    【解决方案2】:

    如果您想显式创建一个比较器,您需要实现一个自定义类,该类具有以下神奇方法:

    class comparator:
            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
    

    这里,函数mycmp 与您展示的函数一样。您还可以选择将您的逻辑直接放在类本身中。在这里,这些方法应该返回一个TrueFalse,这与您当前的函数不同。如果您想将当前函数直接用于此类模板,请确保相应更改。

    一旦你准备好了类,你可以直接传入:key=comparator

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 2020-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-16
      • 2020-02-24
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多