Craig
Craig

Reputation: 1985

Sort a list of objects based on second value of list attribute

I have a list of Car objects, each object being defined as follows:

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)

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:

car_list.sort(key=attrgetter('depreciation_values'))

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?

Upvotes: 1

Views: 458

Answers (2)

wwii
wwii

Reputation: 23753

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[1] < other..depreciation_values[1]

Upvotes: 0

wilkesybear
wilkesybear

Reputation: 528

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[1])

Upvotes: 9

Related Questions