The proper idiom for sorting objects in a list by an arbitrary pr operty

Max Møller Rasmussen maxm at normik.dk
Tue Sep 11 07:07:40 EDT 2001


I have written the below function to sort objects by an arbitrary property.
But I wonder if there is a better way to do it?

Regards Max M

#############################################

def sort(objects, sortAttrib):

    # Sorts a list of objects in accordance to an attribute of choice
    # I assume that Pythons built in sort() is blistering fast
    # So I run around hoops to use that.

    # makes a list of tuples ('value of sortatrib', 'index of object')
    sortValues = [
        (getattr(objects[i], sortAttrib), i) for i in range(len(objects))
                ]
    sortValues.sort(), # Sorts by first value in tuple
    return [objects[sortTuple[1]] for sortTuple in sortValues]

class my:
    def __init__(self, id, title):
        self.id    = id
        self.title = title

m1 = my(1, 'Number one')
m2 = my(2, 'Number two')
m3 = my(3, 'Number three')

for object in sort([m1, m3, m2], 'id'):
    print object.title





More information about the Python-list mailing list