Sorting a list of objects by multiple attributes

Raymond Hettinger python at rcn.com
Tue Apr 11 13:59:31 EDT 2006


[George Young]
>> For multiple keys the form is quite analogous:
>>
>>  L.sort(key=lambda i: (i.whatever, i.someother, i.anotherkey))

[Noah]
> If you are lambda-phobic (as I am) this should also work for an
> arbitrary set of attributes:
>
> attrs = 'attr1 attr2 attr3'.split()
> sortlist = [[getattr(o,a) for a in attrs] + [o] for o in objects]
> sorted_objects = [x[-1] for x in sorted(sortlist)]

The cult of lambda avoidance has lost contact with reality.  Some
Pythonistas now habitually twist their code into knots rather than use
lambda.  The above code fragment is a case in point -- it is shocking
that the poster deems the three-line rewrite as an improvement on
George's clear and succinct code fragment.

Lambda avoidance is rooted in two things, an aversion to the keyword
name and an observation that misuse can result in atrocious code. Also,
some of the use cases have fallen by the wayside with the introduction
of listcomps, genexps, and operator.attrgetter.  Still, some use cases
remain and there is no reason to mangle your code in the name of a
foolish psuedo-principle.

My advice:  use lambda when appropriate and don't feel guilty about it




More information about the Python-list mailing list