sorting ascending/descending with operator.attrgetter

Raymond Hettinger python at rcn.com
Thu Apr 1 00:42:34 CEST 2010


On Mar 31, 10:08 am, Chris Curvey <ccur... at gmail.com> wrote:
> I must be having a brain cramp.  Given a list of objects, how can I
> sort the list on one attribute in descending order, then sort within
> each group in ascending order on another attribute.
>
> For example:
>
> class Foo:
>     def __init__(self, a, b, c):
>         self.a = a
>         self.b = b
>         self.c = c
>
> I can do "allmyfoos.sort(operator.attrgetter('a','b'))" to sort
> ascending on both attributes, but how could i sort by "a, descending,
> then b, ascending)?"

Rely on sort stability and do two passes:

   allmyfoos.sort(operator.attrgetter('b'))
   allmyfoos.sort(operator.attrgetter('a'), reverse=True)


Raymond



More information about the Python-list mailing list