johnhenry johnhenry - 1 year ago 58
Python Question

sorting list of lists and getting indices in unsorted list

These are the logical steps that I need to perform on my list of lists

a = [[5,2],[7,4],[0,3]]

  1. sort the list of lists in such a way that the output looks something like


  2. take the coordinates of the sorted elements in the original list, which in this case should produce as output


I tried using of
sort, sorted
in different ways but I am not getting sensible results, I guess first of all because
can sort a list following only one axis at a time

Answer Source

This code will work for a list of lists. The internal lists don't have to be the same length.

At each level we iterate over a list using enumerate to get the list item and its index. At the top level, each item is another list, and the inner loop iterates over each of those lists to get their indices and values, storing the indices (as a tuple) in a tuple that also contains the value. We then sort the resulting list of tuples (b) on the values, and then split it using zip into a tuple of all the indices and a tuple of the values.

from operator import itemgetter

a = [[5, 2], [7, 4], [0, 3]]

b = [((i, j), v) for i, t in enumerate(a) for j, v in enumerate(t)]
b.sort(key=itemgetter(-1), reverse=True)
coords, vals = zip(*b)


[((1, 0), 7), ((0, 0), 5), ((1, 1), 4), ((2, 1), 3), ((0, 1), 2), ((2, 0), 0)]
(7, 5, 4, 3, 2, 0)
((1, 0), (0, 0), (1, 1), (2, 1), (0, 1), (2, 0))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download