I have a list of Car objects, each object being defined as follows:
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)
The depreciation_values attribute is a list that has 8 components, like below:
[-12.90706937872767, -2.2011534921064739, '-17', '-51.52%', '-7', '-2.75%', '-5', '-1.74%']
The second value (-2.2011534921064739) denotes the depreciation factor and is what I'm trying to use as the sort key.
I'm aware of attrgetter:
But this would sort the list based on the first value of depreciation_values and not the second.
Is there a way to sort all the objects based on the depreciation factor?
You can instead use a lambda in order to access the exact value you want on which to sort:
car_list.sort(key=lambda x: x.depreciation_values)
You could define a
__lt__() (less than) method and other comparison methods to return a boolean based on your desired sort attribute then you could use the built-in sorted() or
list.sort(). "... sort routines are guaranteed to use
__lt__() ... "
class Car: ... def __lt__(self, other): self.depreciation_values < other..depreciation_values