sorting ascending/descending with operator.attrgetter
pmaupin at gmail.com
Wed Mar 31 21:05:24 CEST 2010
On Mar 31, 12:08 pm, 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)?"
You can provide a cmp function to the string sort method, e.g. cmp =
lambda x,y: -cmp(x.a, y.a) or cmp(x.b, y.b)
You can also possibly gain some efficiency by using key instead of
For example, if one of the objects is numeric, you can call sort()
with something like key = lambda x:(-x.a, x.b)
Or if b is numeric but a is a string, you could use lambda x:(x.a, -
x.b) and then use list.reverse() afterward.
More information about the Python-list