我在一个类的列表中有一些元素。我希望它们在新列表中排序,并且必须按照另一个类的属性进行排序。
有人能举个例子吗?
到目前为止我的代码看起来像这样:
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)
我需要self.car_list
按self.license_plate_number
排序 - 最高编号。我不知道到底有多少我不知道。我感谢任何帮助:)
答案 0 :(得分:5)
对具有属性bar
的对象列表进行排序:
anewlist = sorted(list, key=lambda x: x.bar)
答案 1 :(得分:2)
你说你已经有了课程(显示它们!)所以你可以通过定义__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