我有一个Car对象列表,每个对象定义如下:
class Car:
def __init__(self, vin, name, year, price, weight, desc, owner):
self.uid = vin
self.name = name
self.year = year
self.price = price
self.weight = weight
self.desc = desc
self.owner = owner
self.depreciation_values = self.get_depreciation_values(name, vin)
折旧值属性是一个包含8个组件的列表,如下所示:
[-12.90706937872767, -2.2011534921064739, '-17', '-51.52%', '-7', '-2.75%', '-5', '-1.74%']
第二个值(-2.2011534921064739)表示折旧因子,是我试图用作排序键的。
我知道attrgetter:
car_list.sort(key=attrgetter('depreciation_values'))
但是这将根据第一个值而不是第二个值对列表进行排序。
是否有一种方法可以根据折旧因子对所有对象进行排序?
您可以使用lambda来访问您想要排序的确切值:
car_list.sort(key=lambda x: x.depreciation_values[1])
您可以定义__lt__()
(小于)方法和其他比较方法来返回基于所需排序属性的布尔值,然后您可以使用内置的sorted()或list.sort()
。"…排序例程保证使用__lt__
()…"
class Car:
...
def __lt__(self, other):
self.depreciation_values[1] < other..depreciation_values[1]