如何对Python对象排序

2024-04-20 03:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)

Tags: 对象inselfid列表错误整数item
2条回答

如果要按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的功能,您只需要定义其中一个方法,它将负责其余的方法

^{pr2}$

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内置函数提供显式的键函数:

^{pr2}$

相关问题 更多 >