I have a list of objects instantiated from a class. I need to sort the list using 'x' and 'is_start' parameters.
I tried using the total_ordering module from functools and custom wrote the lt & eq methods.
Class:
@total_ordering
class BuildingPoint(object):
def __init__(self):
self.x = None
self.height = None
self.is_start = None
def __lt__(self, other):
if self.x != other.x:
return self.x < other.x
def __eq__(self, other):
if self.x == other.x:
# If both points are starting points then building with higher height
# comes earlier
if self.is_start and other.is_start:
return self.height > other.height
# If both points are ending points then building with lower height
# comes earlier
if not self.is_start and not other.is_start:
return self.height < other.height
Now if I want to sort this list of BuildingPoint objects where the first and third objects have same x and is_start:
building_points = [[0, 2, True], [1, 2, False], [0, 3, True], [2, 3, False]]
Sorting building_points should give this output:
sorted(building_points)
>>[[0, 3, True], [0, 2, True], [1, 2, False], [2, 3, False]]
But it's returning the same object list. Any advice on how to do this?