我有一个 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)
depreciation_values 属性是一个包含 8 个组件的列表,如下所示:
[-12.90706937872767, -2.2011534921064739, '-17', '-51.52%', '-7', '-2.75%', '-5', '-1.74%']
第二个值 (-2.2011534921064739) 表示折旧系数,这是我试图用作排序键的值。
我知道 attrgetter:
car_list.sort(key=attrgetter('depreciation_values'))
但这会根据 depreciation_values 的第一个值而不是第二个值对列表进行排序。
有没有办法根据折旧系数对所有对象进行排序?
请您参考如下方法:
您可以改为使用 lambda 来访问您想要排序的确切值:
car_list.sort(key=lambda x: x.depreciation_values[1])
