Simpler way of sorting list of lists indexed by one list in Python
Question: I want to sort a list of two lists, where the elements in the two lists are
pairs.

I want to sort the lists by the second element in these pairs.

For example if I have

    
    
    a_list = [[51132, 55274, 58132], [190, 140, 180]]
    

and want

    
    
    sorted_list = [[55274, 58132, 51132], [140, 180, 190]]
    

Is there a simpler way than the following in Python2.7?

    
    
    from operator import itemgetter
    sorted_list = map(list, zip(*sorted(map(list,zip(*a_list)), key=itemgetter(1))))
    

Best regards, Øystein


Answer: I am a bit reluctant to post this as an answer, but why not, actually?

No, there is no simpler way to achieve your sort in Python -- except that you
can drop that inner `map`:

    
    
    >>> map(list, zip(*sorted(zip(*a_list), key=itemgetter(1))))
    [[55274, 58132, 51132], [140, 180, 190]]
    

It may seem a bit convoluted at first (though not as much as _with_ that
additional `map`), but actually it's totally clear: You _zip_ the list, _sort_
by the second element, and _zip_ it back. Everyone who knows Python should
understand what the code does.

If you want to make it even clearer, either add a line comment describing what
the sort does, or wrap it inside a function with a descriptive name and the
same or a more extensive comment.

