Skip to content

Instantly share code, notes, and snippets.

@gibtang
Created June 6, 2020 10:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gibtang/83f9681b525908900ec4b490992f032d to your computer and use it in GitHub Desktop.
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
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)
print
sorted_car_name.sort()
print(sorted_car_name)
print
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