使用范围使用自定义排序功能对元组进行排序?

Coc*_*ico 2 python sorting tuples custom-function

我想根据最后两列对元组列表进行排序:

mylist = [(33, 36, 84), 
          (34, 37, 656), 
          (23, 38, 42)]
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

final = sorted(mylist, key:lambda x: [ x[1], x[2]])
Run Code Online (Sandbox Code Playgroud)

现在我的问题是我想要将列表的第二列与特殊条件进行比较:如果两个数字之间的差异小于偏移量,则应将它们视为相等(36 == 37 == 38)和第三列应该用于对列表进行排序.我希望看到的最终结果是:

mylist = [(23, 38, 42)
          (33, 36, 84), 
          (34, 37, 656)]
Run Code Online (Sandbox Code Playgroud)

我在考虑创建自己的整数类型并覆盖等于运算符.这可能吗?这有点难过吗?有没有更好的方法来解决这个问题?

MSe*_*ert 5

我认为最简单的方法是创建一个比较你想要的新类:

mylist = [(33, 36, 84), 
          (34, 37, 656), 
          (23, 38, 42)]

offset = 2

class Comp(object):
    def __init__(self, tup):
        self.tup = tup

    def __lt__(self, other):  # sorted works even if only __lt__ is implemented.
        # If the difference is less or equal the offset of the second item compare the third
        if abs(self.tup[1] - other.tup[1]) <= offset:
            return self.tup[2] < other.tup[2]
        # otherwise compare them as usual
        else:
            return (self.tup[1], self.tup[2]) < (other.tup[1], other.tup[2])
Run Code Online (Sandbox Code Playgroud)

示例运行显示您的预期结果:

>>> sorted(mylist, key=Comp)
[(23, 38, 42), (33, 36, 84), (34, 37, 656)]
Run Code Online (Sandbox Code Playgroud)

我认为它比使用functools.cmp_to_key更清洁,但这是个人偏好的问题.