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:
       
==========================================================   
def sort_tuple_list_by_2nd_elements(alist):
    """
    Return a list of 2-element tuples, with the list
    sorted by the 2nd element of the tuples.
    """
    e0_list = []
    e1_list = []
   
    for e in alist:
        e0_list.append(e[0])
        e1_list.append(e[1])
    e1_list_sorted = sorted(e1_list)
   
    alist_sorted_by_e1 = []
    for i, e0 in enumerate(e1_list_sorted):
        alist_sorted_by_e1.append((e0_list[i], e0))
    return alist_sorted_by_e1
   
if __name__ == '__main__':
    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?

BTW what list comprehension would have accomplished the same thing as my function?

Thanks,

Dick Moores
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to