Python - How to sort a list, by an attribute from another class

守給你的承諾、 提交于 2020-01-30 12:15:08

问题


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 :)


回答1:


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

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



回答2:


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


来源:https://stackoverflow.com/questions/4648608/python-how-to-sort-a-list-by-an-attribute-from-another-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!