gpt4 book ai didi

python - 如何对 Python 对象进行排序

转载 作者:太空狗 更新时间:2023-10-29 18:05:57 25 4
gpt4 key购买 nike

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

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你可以使用 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 - 如何对 Python 对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29811547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com