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 exa
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
To sort a list of objects that have the attribute bar
:
anewlist = sorted(list, key=lambda x: x.bar)