Terry Carroll wrote: > 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.)
As long as your list-like object is list-like enough to be sorted, you can use operator.attrgetter to create functions that serve as a key parameter. In [1]: class foo(object): ...: def __init__(self, a, b, c): ...: self.a = a; self.b = b; self.c = c ...: def __repr__(self): ...: return repr((self.a, self.b, self.c)) ...: ...: In [2]: lst = [foo(1, 'one', 'I'), foo(2, 'two', 'II'), foo(10, 'ten', 'X'), foo(50, 'fifty', 'V')] In [7]: lst Out[7]: [(1, 'one', 'I'), (2, 'two', 'II'), (10, 'ten', 'X'), (50, 'fifty', 'V')] In [8]: from operator import attrgetter In [9]: lst.sort(key=attrgetter('b')); print lst [(50, 'fifty', 'V'), (1, 'one', 'I'), (10, 'ten', 'X'), (2, 'two', 'II')] In [10]: lst.sort(key=attrgetter('c')); print lst [(1, 'one', 'I'), (2, 'two', 'II'), (50, 'fifty', 'V'), (10, 'ten', 'X')] Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor