1

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?

3
  • 1
    @Delgan 'operator.attrgetter' object is not subscriptable. Commented Aug 30, 2016 at 19:37
  • @L3viathan Oups, indeed. wilkesybear is the best solution anyway. Commented Aug 30, 2016 at 19:40
  • @Delgan It could totally be made working, but I guess it'd be too much magic for the standard library. Commented Aug 30, 2016 at 20:29

2 Answers 2

9

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])
Sign up to request clarification or add additional context in comments.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.