[Tutor] I need to learn more about sorting!

Jerry Hill malaclypse2 at gmail.com
Mon Jun 23 22:18:10 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. I
> couldn't see a ready-made function around to do this, so I rolled my own:
...
>     colors = [('khaki4', (139, 134, 78)), ('antiquewhite', (250, 235, 215)),
> ('cyan3', (0, 205, 205)), ('antiquewhite1', (238, 223, 204)),
> ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ]
>
>     print sort_tuple_list_by_2nd_elements(colors)
>
> """
> 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))]
> """
> ==================================================================
> 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?

Did that really work the way you wanted!?  It switched elements around
between tuples, which doesn't seem right.  For example, in the input
list you had ('khaki4', (139, 134, 78)) in the output list that became
('khaki4', (0, 205, 205)).

Assuming you just want to sort the list of tuples by the second
element without actually changing the tuples, you can do the
following:

>>> colors = [('khaki4', (139, 134, 78)), ('antiquewhite', (250, 235, 215)), ('cyan3', (0, 205, 205)), ('antiquewhite1', (238, 223, 204)), ('dodgerblue4', (16, 78, 139)), ('antiquewhite4', (139, 131, 120)), ]

>>> from operator import itemgetter
>>> sorted_colors = sorted(colors, key=itemgetter(1))
>>> sorted_colors
[('cyan3', (0, 205, 205)), ('dodgerblue4', (16, 78, 139)),
('antiquewhite4', (139, 131, 120)), ('khaki4', (139, 134, 78)),
('antiquewhite1', (238, 223, 204)), ('antiquewhite', (250, 235, 215))]
>>>

-- 
Jerry


More information about the Tutor mailing list