0
votes

I have some elements in a list in one class. I want them sorted in a new list, and they have to be sorted by an attribute from another class.

Can anyone give an example?

My code so far looks like this:

class Carcompany:
  def __init__(self, model, production_number):
    self.model = model
    self.production_number = production_number
    self.car_list = []

  def add_car_to_car_list(self, car):
    self.car_list.append(car)

class Info:
  def __init__(self):
    self.license_plate_number = []

  def add_license_plate_to_list(self, license_plate):
    self.license_plate_number.append(license_plate)

I need self.car_list to be sorted by self.license_plate_number - highest number first. I don't know how much I'm missing to get there. I appreciate any help I can get :)

2
You should give us a quick example of how the original list is stored, and what the elements look like. - Brandon Rhodes
The list looks like: ["car1", "car2", "car3"] - and I want them to be sorted by license plate number, which is an attribute in another class called Info. They have to be sorted with the highest number first. - Python_Noob
How are the items in the list related to the attribute in the other class -- i.e. how would one look-up the license plate number of a given car? - martineau
The license plate number is in a list, and then I add that to car1, using append - Python_Noob
Sounds like car1 is a list if you're using append() to add a license plate number to it -- but previous you said the list was ["car1", "car2", "car3"] which is a list of strings. Please show the classes and lists involved (by editing your question). - martineau

2 Answers

4
votes

To sort a list of objects that have the attribute bar:

anewlist = sorted(list, key=lambda x: x.bar)
2
votes

You say that you have classes already (show them!) so you can make them sortable by defining __lt__:

class Car(object):
    def __init__(self, year, plate):
        self.year = year
        self.plate = plate

    # natural sort for cars by year:
    def __lt__(self, other):
        return self.year < other.year

    def __repr__(self):
        return "Car (%d) %r" % (self.year, self.plate)

class Plate(object):
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return repr(self.val)

    # natural sort by val:
    def __lt__(self, other):
        return self.val < other.val

cars = [ Car(2009, Plate('A')),
              Car(2007, Plate('B')),
              Car(2006, Plate('C'))
]

print cars
print sorted(cars) # sort cars by their year
print sorted(cars, key=lambda car: car.plate) # sort by plate