-2

I'm asking this question because none of the answers given here: Sort a list by multiple attributes? work for me.

I've built a web scraper for an online market. I get the price, year of production and location of the car (city where the seller lives). I want to sort the list that by the price (lower price = better), year of production (newer = better), and the distance from the seller to buyer (i will calculate it with geopy, and shorter distance = better) so I can find the best car for the buyer. I tried using sorted() but I didn't manage to get it to work.

Here is what my list looks like:

The tuples are formatted like this: (price, year of production, distance)

cars_info = [(10000, 2013, 40), (13000, 2012, 50), (20000, 2016, 100)]
Andrej
  • 2,743
  • 2
  • 11
  • 28

1 Answers1

1

The builtinsorted with a custom key will easily achieve what you need, e.g.

sorted(cars_info, key=lambda x:(x[0], -x[1], x[2]))

Given the fact that sorted sorts numeric elements ascendingly and from left to right, manipulating signs gives you control on what you want sorted which way (ascending vs descending) and the order gives you control on what are the most important features (i.e. which ones to consider first)

Lukas Thaler
  • 2,672
  • 5
  • 15
  • 31