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

后端 未结 2 627
北海茫月
北海茫月 2020-12-22 07:50

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

相关标签:
2条回答
  • 2020-12-22 08:35

    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
    
    0 讨论(0)
  • 2020-12-22 08:37

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

    anewlist = sorted(list, key=lambda x: x.bar)
    
    0 讨论(0)
提交回复
热议问题