Given a list of Objects, find the minimum and maximum value on the basis of an object property in Python.
For Example, from a list of cars and find out which car has will come first and last in terms of their max speed.
To do this, we have to
- Declare a class named
carwith max_speed as one of its properties.
- Create list of car’s objects.
- Find the minimum and maximum of the objects on the basis of
def __init__(self, max_speed):
self.name = name
self.max_speed = max_speed
#create objects list
cars_list = [Car('Nano', 258), Car('Ferrari', 337), Car('Maruti', 501)]
#Find car with maximum speed
first = max(cars_list, key=lambda car: car.max_speed)
#Find car with minimum speed
last = min(cars_list, key=lambda car: car.max_speed)
print('Car with Maximum Speed: ',first.name)
print('Car with Minimum Speed: ',last.name)
Car with Maximum Speed: Maruti
Car with Minimum Speed: Nano
If you have any doubts or suggestion then please comment below.