Home > Enterprise >  Getting indices of a sorted list of lists in Python
Getting indices of a sorted list of lists in Python

Time:07-28

I have a list of lists called test and I am trying to get the array locations when the elements of test are sorted in an increasing order. For example, I am looking for ans for a sample test as shown below.

test=[[1,2],[3,4]]
ans=[[0,0],[0,1],[1,0],[1,1]]

The array locations of 1,2,3,4 are as described in the ans above. Any suggestions? I can use a numpy array instead of a list of lists if that makes the job easier.

CodePudding user response:

I hope I've understood your question right. You can flatten your list to a list with indices and then sort it (assuming the test isn't pre-sorted):

test = [[1, 2], [3, 4]]

out = [
    l
    for _, l in sorted(
        ((v, [i, j]) for i, l in enumerate(test) for j, v in enumerate(l))
    )
]
print(out)

Prints:

[[0, 0], [0, 1], [1, 0], [1, 1]]
  • Related