Python 3カスタム比較ソート/演算子

2840 ワード

Python 3はPython 2に比べてかなり変化しています.
Python 2ではcmp関数を直接パラメータとしてsortに入力してソートを定義することができますが、Python 3はキャンセルされました.
ここでPython 3のカスタムソートの2つの書き方をまとめ、補足を歓迎します.
並べ替えられるデータ構造として2次元空間の点を用い,xを比較してからyを比較することを望んでいる.
class Pos:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

    def __str__(self):
        return ('(%s, %s)' % (self.x, self.y))

    __repr__ = __str__

1.cmp関数
最初の方法はcmpやlambda式を書き換える形でPython 2と似ています
このメソッドはsortedではうまくソートできません.
functoolsを借りるだけ
import functools
def cmp(a, b):
    return a.x-b.x if a.x != b.x else a.y-b.y  # x y          

if __name__ == '__main__':

    test_list = [Pos(5, 1), Pos(2,5), Pos(2, 4)]
    # test_list.sort(key=functools.cmp_to_key(lambda a,b: a.x-b.x if a.x != b.x else a.y-b.y))
    test_list.sort(key=functools.cmp_to_key(cmp))
    # sorted(test_list, key=functools.cmp_to_key(cmp))  #               
    print(test_list)  #      [(2, 4), (2, 5), (5, 1)]

2.クラスメソッドの書き換え
Python 2で直接書き換えることができます_cmp__方法は比較を実現するが、Python 3ではキャンセルされている.
Python 3では各比較演算子を細分化する必要がある.
__lt__: <
__gt__: >
__ge__: >=
__eq__: ==
__le__: <=

次のように実現
class Pos:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y

    def __str__(self):
        return ('(%s, %s)' % (self.x, self.y))

    def __lt__(self, other):
        print('lt: ' + str(self))
        return self.x < other.x if self.x != other.x else self.y < other.y

    def __gt__(self, other):
        print('gt: ' + str(self))
        return self.x > other.x if self.x != other.x else self.y > other.y

    def __ge__(self, other):
        print('ge: ' + str(self))
        return self.x >= other.x if self.x != other.x else self.y >= other.y

    def __eq__(self, other):
        print('eq: ' + str(self))
        return self.x == other.x and self.y == other.y

    def __le__(self, other):
        print('le: ' + str(self))
        return self.x <= other.x if self.x != other.x else self.y <= other.y

    __repr__ = __str__

実践してみましょう
if __name__ == '__main__':

    if Pos(5,1) <= Pos(2,4):
        print('True!')
    if Pos(5,1) == Pos(2,4):
        print('True!')
    if Pos(5,1) > Pos(2,4):
        print('True!')
#   
# le: (5, 1)
# eq: (5, 1)
# gt: (5, 1)
# True!

最後にソートに戻ります
if __name__ == '__main__':

    test_list = [Pos(5, 1), Pos(2,5), Pos(2, 4)]
    test_list.sort()
    print(test_list)

    test_list.sort(reverse=True)
    print(test_list)

#   
# lt: (2, 5)
# lt: (2, 4)
# [(2, 4), (2, 5), (5, 1)]
# lt: (2, 5)
# lt: (2, 4)
# [(5, 1), (2, 5), (2, 4)]