Fun with reverse sorts

Chris Rebert clp at rebertia.com
Fri Oct 3 00:08:36 EDT 2008


On Thu, Oct 2, 2008 at 8:07 PM, David Di Biase <dave.dibiase at gmail.com> wrote:
> Hi there,
>
> I'm sorting an expansive list descending according to a list of tuples.
> Basically it has to sort the last value in the tuple (3) but if they are the
> same then it should resort to using the second last value (2). Now according
> to my very limited testing I've somewhat figured out that this SHOULD work:
>
> list.sort(lambda a, b: (cmp(a[3], b[3]), cmp(a[2], b[2])) [a[3] == b[3]],
> reverse = True)

Rather than defining a comparison function here (which is less
efficient), you can use the 'key' argument, which specifies a function
which is called for each item and returns a so-called key value that
the corresponding element should be sorted according to. Also, so your
slicing "[a[3] == b[3]]" isn't necessary because Python is smart and
sorts tuples that way anyway. Finally, be careful not to use "list" as
a variable name as this shadows the builtin 'list' type.

So the improved code is:

your_list.sort(key=lambda elem: (elem[3], elem[2]), reverse=True)

>
> Here's an example of the list: [(34,23,54,34), (34,23,230,34),
> (34,23,523,334), (34,23,15,17), (34,23,54,17), (45,23,43,123),
> (564,23,543,23), (23,54,600,23), (34,54,23,654), (43,54,32,34)]
>
> My first question is in regards to style first. The style guide for Python
> doesn't seem to state this (if it has I missed it) but should I be doing
> reverse=True or reverse = True with the spaces. lol this is so miniscule but
> it's good to know. Also, does this function look/feel right to all the pros
> out there. Is there a better way of doing it?

Actually, this is mentioned in PEP 8. You might not be familiar with
the term in use though ("keyword argument") which describes 'reverse'.
Here's the relevant section:

"""
- Don't use spaces around the '=' sign when used to indicate a
      keyword argument or a default parameter value.

      Yes:

          def complex(real, imag=0.0):
              return magic(r=real, i=imag)

      No:

          def complex(real, imag = 0.0):
              return magic(r = real, i = imag)
"""

So you want the former: reverse=True

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> I'm still wrapping my head around ways of accomplishing proper sorts!
>
> Dave
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



More information about the Python-list mailing list