Python 使用类参数中的条件对类对象列表进行排序
我有一个从类实例化的对象列表。我需要使用“x”和“is_start”参数对列表进行排序 我尝试使用functools中的total_排序模块,并自定义编写了lt&eq方法 类别: @总订单 类BuildingPointobject: 定义初始自我: self.x=无 self.height=无 self.is_start=无 定义自身,其他: 如果self.x!=其他.x: 返回self.xPython 使用类参数中的条件对类对象列表进行排序,python,sorting,functools,Python,Sorting,Functools,我有一个从类实例化的对象列表。我需要使用“x”和“is_start”参数对列表进行排序 我尝试使用functools中的total_排序模块,并自定义编写了lt&eq方法 类别: @总订单 类BuildingPointobject: 定义初始自我: self.x=无 self.height=无 self.is_start=无 定义自身,其他: 如果self.x!=其他.x: 返回self.xother.height 如果两个点都是终点,则建筑高度较低 来得早 如果不是self.is\u star
但它返回的是同一个对象列表。有什么建议吗 正如@juanpa.arrivillaga提到的,你的uu lt_uuu和uu eq_uu都坏了。我刚刚修好了,去掉了,我想这就是你想要做的。 此外,您正在排序数组列表,而不是BuildingPoint对象。我修复了从数组创建构建点的u u init。最后,我添加了一个_repr__________)方法来显示对象 我不确定你是否想这么做,以下是我所做的:
from functools import total_ordering
@total_ordering
class BuildingPoint(object):
def __init__(self,x,h,start):
self.x = x
self.height = h
self.is_start = start
def __repr__(self):
return "[{},{},{}]".format(self.x,self.height,self.is_start)
def __lt__(self, other):
if self.x != other.x:
return self.x < other.x
else:
if self.is_start and other.is_start:
return self.height > other.height
else:
return self.height < other.height
building_points = [ BuildingPoint(*array) for array in [[0, 2, True], [1, 2, False], [0, 3, True], [2, 3, False]]]
sorted(building_points)
首先,你的函数坏了,它可以不返回任何值。与您的uuu eq uuu函数相同,对于您的uuu lt uuuu方法,您可以只返回self.x
[[0,3,True], [0,2,True], [1,2,False], [2,3,False]]