[Tutor] Sorting a list of objects on different fields
Terry Carroll
carroll at tjc.com
Thu Mar 2 22:03:27 CET 2006
I have a list (or a list-like object, doesn't matter) of objects, each of
which has multiple fields. I want to be able to arbitrarily sort the list
on any of them, or at least on several of them.
To make this a little more concrete, here's a simplified idea. Say the
objects each represent a file, and I've got fields in it
like this:
self.filesz: size of the file
self.filename: name of the file
self.users : a list of people who need to know if the file gets updated
self.filetype : a short description of the file contents
etc.
I sometimes want to sort the list by filesz; and sometimes by filename;
and maybe sometimes by some other field.
My sense right now is that the "list" of these objects itself should be an
object inheriting from list, and that I should create a small sort method
for each field I intend to sort on. (I don't have the book handy, but
there's a nice recipe for this in the Python Cookbook, 2d Edition, for
such a method.)
Is there a better (more clear and easy) way to be able to do this, or
am I pretty much on the right track?
More information about the Tutor
mailing list