I have a nested list which contains different objects, they're duplicate pairs of objects in the nested list and i'm trying to remove them but i keep getting a
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)
If you want to compare the objects by the 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>]]
Depending on the functionality you want to implement all the rich comparison ordering methods you can use functools.total_ordering, you just need to define one of the methods and it will take care of the rest
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.