如何对 Python 个对象进行排序

How to Sort Python Objects

我有一个包含不同对象的嵌套列表,它们是嵌套列表中的重复对象对,我试图删除它们,但我一直收到

TypeError: unorderable types: practice() < practice()

我知道这个错误是由于我尝试使用对象而不是整数引起的,但我不知道还有什么方法可以删除重复项,这是我尝试过的方法

class practice:
    id = None

    def __init__(self,id):
        self.id = id

a = practice('a')
b = practice('b')
c = practice('c')
d = practice('d')
e = practice('e')
f = practice('f')

x = [[a,b],[c,d],[a,b],[e,f],[a,b]]

unique_list = list()
for item in x:
    if sorted(item) not in unique_list:
        unique_list.append(sorted(item))

print(unique_list)

如果你想通过id比较对象:

class practice:
    id = None

    def __init__(self,id):
        self.id = id

    def __lt__(self, other):
        return other.id > self.id

    def __gt__(self, other):
        return self.id > other.id

unique_list = list()
for item in x:
    if sorted(item) not in unique_list:
        unique_list.append(sorted(item))

print(unique_list)
[[<__main__.practice object at 0x7fe87e717c88>, <__main__.practice object at 0x7fe87e717cc0>],
 [<__main__.practice object at 0x7fe86f5f79e8>, <__main__.practice object at 0x7fe86f589278>],
 [<__main__.practice object at 0x7fe86f589be0>, <__main__.practice object at 0x7fe86f589c18>]]

根据您要实现的所有功能,rich comparison ordering methods you can use functools.total_ordering,您只需定义其中一种方法,其余的将由它处理

from functools import total_ordering
@total_ordering
class practice:
    id = None

    def __init__(self,id):
        self.id = id

    def __lt__(self, other):
        return other.id > self.id

    def __eq__(self, other):
        return self.id == other.id

Given a class defining one or more rich comparison ordering methods, this class decorator supplies the rest. This simplifies the effort involved in specifying all of the possible rich comparison operations:

The class must define one of __lt__(), __le__(), __gt__(), or __ge__(). In addition, the class should supply an __eq__() method.

要支持 Python 3 中的对象在没有显式键的情况下进行排序,您必须实现 __lt__ 特殊方法:

class practice:
    id = None

    def __init__(self,id):
        self.id = id

    def __lt__(self, other):
        return self.id < other.id

如果您希望其他运算符工作,您也必须实现它们的特殊方法,但是对于排序 __lt__ 是您所需要的。

如评论中所述,另一种方法是为 sorted 内置函数提供显式键函数:

sorted(item, key=lambda x: x.id)