[Tutor] I need to learn more about sorting!

Kent Johnson kent37 at tds.net
Mon Jun 23 22:30:24 CEST 2008


On Mon, Jun 23, 2008 at 4:06 PM, Dick Moores <rdm at rcblue.com> wrote:
> I needed to sort a list of 2-element tuples by their 2nd elements.

We just talked about this:
http://thread.gmane.org/gmane.comp.python.tutor/48646/

> I
> couldn't see a ready-made function around to do this, so I rolled my own:
>
> """
> OUTPUT:
> [('khaki4', (0, 205, 205)), ('antiquewhite', (16, 78, 139)), ('cyan3', (139,
> 131, 120)), ('antiquewhite1', (139, 134, 78)), ('dodgerblue4', (238, 223,
> 204)), ('antiquewhite4', (250, 235, 215))]
> """

Is that really what you want? You have sorted the second element of
the list independently of the first - the order of first elements
hasn't changed.

> ==================================================================
> It works, but did I really need to roll my own? I think I wouldn't have had
> to if I understood what arguments to use for either of the built-ins, sort()
> or sorted(). Can someone give me a clue?
>
> BTW what list comprehension would have accomplished the same thing as my
> function?

If you really want to sort the second element separately, you could use
e0_list, e1_list = zip(*alist)
e1_list = sorted(e1_list) # Have to use sorted; e1_list is a tuple
alist_sorted_by_e1 = zip(e0_list, e1_list)

Kent


More information about the Tutor mailing list