Sorting a list of objects by multiple attributes

nghoffma nghoffma at gmail.com
Tue Apr 11 22:41:25 EDT 2006


I'm sure my avoidance of lambdas as due as much to laziness as
adherence to principle. This is a good opportunity to learn about them.


I suggested the above because it wasn't obvious to me how one would
pass the arbitrary set of attributes to the lambda expression (and I
envisioned them being specified as strings in this case, since the set
of attributes will be coming from a web form).

So what about the following (attrgetter aside)?

attrs = 'attr1 attr2 attr3'.split()
L.sort(key=lambda i: [getattr(i,a) for a in attrs])

-Noah




More information about the Python-list mailing list