I'm teaching myself Python from a book and I'm stuck on a programming exercise. The aim of the exercise is to make a list of objects, and then sort those objects based on some object attribute.
The author of my textbook says that using a key to call a class method for every comparison during sorting can slow down sort time for large datasets and that building a 'decorated' list by calling the class method just once for each object as you build the list can make subsequent sorting more efficient. The programming problem stipulates that, instead of a key, I should make a series of tuples, wherein tuple element 0 is the literal value of an object attribute, and tuple element 1 is the object itself. After I have my decorated list, I can use a built-in list sort method (e.g. "sorted()" or ".sort()", etc.) to put it all in order.
I get an error when two objects have an identical sort attribute value. This example code will reproduce the error:
class Shrubber:
def __init__(self, age):
self.name = 'Roger'
self.age = age
def getAge(self):
return self.age
def main():
rogerAges = [30, 21, 21, 25]
rogers = []
for rAge in rogerAges:
newShr = Shrubber(rAge)
rogers.append((newShr.getAge(), newShr))
rogers.sort()
print(rogers)
main()
I would like the program to print something like this:
[(21, <__main__.Shrubber object at XxXEX>), (21, <__main__.Shrubber object at YxYEY>), (25, <__main__.Shrubber object at ZxZEZ>), (30, <__main__.Shrubber object at QxQEQ>)]
...but instead, it gives me a TypeError:
TypeError: unorderable types: Shrubber() < Shrubber()
I'm sure I'm getting the error because, after Python encounters two identical values for two tuple elements 0, it looks to elements 1 and finds an unorderable data type (an object). However, the limitation that two Shrubbers can't be the same age makes it seem like I'm missing something.
My question: Can I stably sort my tuple list by tuple element 0 and ignore my unorderable tuple element 1?