Sorting a list of objects by multiple attributes

Raymond Hettinger python at rcn.com
Wed Apr 12 14:59:20 EDT 2006


[Noah]
> 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])

When starting with attribute names in a list of strings,
this code looks fine.  The Py2.5 version of attrgetter
will be even cleaner:

    L.sort(key=attrgetter(*attrs))




More information about the Python-list mailing list