sorting ascending/descending with operator.attrgetter
Raymond Hettinger
python at rcn.com
Wed Mar 31 18:42:34 EDT 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