Q: sort's key and cmp parameters

kj no.email at please.post
Thu Oct 1 18:05:24 EDT 2009


In <ec18cfe1-e122-499e-be5e-0bf1bdbb7c07 at t11g2000prh.googlegroups.com> Raymond Hettinger <python at rcn.com> writes:

<snip>

Thanks for an extremely helpful reply!

>If you need to sort by an ascending primary key and a descending
>secondary key, you may find it easiest to sort in two passes
>(taking advantage of guaranteed sort stability):

>    sorted(s, key=secondary, reversed=3DTrue)
>    sorted(s, key=primary)

In the special case where the value returned by secondary is
numeric, I suppose one could do this in one go with

  sorted(s, key=lambda x: (primary(x), -secondary(x)))

...but I can't think of a way to generalize this...

kj



More information about the Python-list mailing list