[Tutor] sorting objects on two attributes

Kent Johnson kent37 at tds.net
Mon Mar 3 17:34:35 CET 2008

Chris Fuller wrote:
> You could have a hierarchical sort 
> function:
> def hiersort(a,b):
>    if a.attr1 != b.attr1:
>       return cmp(a.attr1, b.attr1)
>    else:
>       if a.attr2 != b.attr2:
>          return cmp(a.attr2, b.attr2)
>       else:
>          return cmp(a.attr3, b.att3)
> l.sort(hiersort)

That is exactly what l.sort(key=lambda x: (x.attr1, x.attr2, x.attr3)) 
does, except the key= version is simpler and most likely faster.

You can also use
   l.sort(key=operator.attrgetter('attr1', 'attr2', 'attr3'))

> You can keep nesting for more than three attributes, or you could make it 
> arbitrary by setting it up recursively and setting the attribute hierarchy as 
> a parameter somewhere.  But that's probably unnecessarily fancy.

should work...


More information about the Tutor mailing list