Created
June 6, 2020 10:10
-
-
Save gibtang/83f9681b525908900ec4b490992f032d to your computer and use it in GitHub Desktop.
Simple sort of objects in a list using an attribute of type string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class cars: | |
def __init__(self, name, price): | |
self.name = name | |
self.price = price | |
unsorted_cars = [] | |
unsorted_cars.append(cars('Ford', 20000)) | |
unsorted_cars.append(cars('Volvo', 50000)) | |
unsorted_cars.append(cars('BMW', 24000)) | |
unsorted_cars.append(cars('Toyota', 15000)) | |
unsorted_cars.append(cars('Kia', 12000)) | |
unsorted_cars.append(cars('Audi', 40000)) | |
unsorted_cars.append(cars('Tesla', 30000)) | |
print("List of cars unsorted by name") | |
for car in unsorted_cars: | |
print(car.name + " and price is " + str(car.price)) | |
sorted_car_name = [] | |
for car in unsorted_cars: | |
sorted_car_name.append(car.name) | |
sorted_car_name.sort() | |
print(sorted_car_name) | |
sorted_car = [] | |
for sort_car in sorted_car_name: | |
for unsorted_car in unsorted_cars: | |
if unsorted_car.name == sort_car: | |
sorted_car.append(unsorted_car) | |
break | |
for car in sorted_car: | |
print("Sorted " + car.name + " and price is " + str(car.price)) | |
###Using the sorted command### | |
print("Using unsorted function") | |
result = sorted(unsorted_cars, key=lambda cars: cars.name) | |
for car in result: | |
print(car.name + " and price is " + str(car.price)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment