<html>
<body>
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:<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br>
<tt>
==========================================================&nbsp;&nbsp;&nbsp;
<br>
def sort_tuple_list_by_2nd_elements(alist):<br>
&nbsp;&nbsp;&nbsp; &quot;&quot;&quot;<br>
&nbsp;&nbsp;&nbsp; Return a list of 2-element tuples, with the list <br>
&nbsp;&nbsp;&nbsp; sorted by the 2nd element of the tuples.<br>
&nbsp;&nbsp;&nbsp; &quot;&quot;&quot;<br>
&nbsp;&nbsp;&nbsp; e0_list = []<br>
&nbsp;&nbsp;&nbsp; e1_list = []<br>
&nbsp;&nbsp;&nbsp; <br>
&nbsp;&nbsp;&nbsp; for e in alist:<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e0_list.append(e[0])<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; e1_list.append(e[1])<br>
&nbsp;&nbsp;&nbsp; e1_list_sorted = sorted(e1_list)<br>
&nbsp;&nbsp;&nbsp; <br>
&nbsp;&nbsp;&nbsp; alist_sorted_by_e1 = []<br>
&nbsp;&nbsp;&nbsp; for i, e0 in enumerate(e1_list_sorted):<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
alist_sorted_by_e1.append((e0_list[i], e0))<br>
&nbsp;&nbsp;&nbsp; return alist_sorted_by_e1<br>
&nbsp;&nbsp;&nbsp; <br>
if __name__ == '__main__':<br>
&nbsp;&nbsp;&nbsp; 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)), ]<br>
&nbsp;&nbsp;&nbsp; <br>
&nbsp;&nbsp;&nbsp; print sort_tuple_list_by_2nd_elements(colors)<br>
&nbsp;&nbsp;&nbsp; <br>
&quot;&quot;&quot;<br>
OUTPUT:<br>
[('khaki4', (0, 205, 205)), ('antiquewhite', (16, 78, 139)), ('cyan3',
(139, 131, 120)), ('antiquewhite1', (139, 134, 78)), ('dodgerblue4',
(238, 223, 204)), ('antiquewhite4', (250, 235, 215))]<br>
&quot;&quot;&quot;<br>
==================================================================<br>
</tt>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?<br><br>
BTW what list comprehension would have accomplished the same thing as my
function?<br><br>
Thanks,<br><br>
Dick Moores<br>
</body>
</html>