Home > Enterprise >  How to show an order index of array
How to show an order index of array

Time:01-26

I have this array:

A=[5,20,13,1]

I want a way to make an array that returns the index after the sort. I know about argsort, which result is the index before is sorted, in this case, the result is [3,0,2,1]

But, I need to have an array that shows the index after is sort:

[1,3,2,0]

The first element shows that 1 is the smallest element (and its index 0 in a fictional array sorted). Like a classification table without losing the order in A.

CodePudding user response:

First, get the positions after sorting - make sure you append to a list or a deque as you might have the same number multiple times.

Then create a new list based on these indices.

Handles duplicate values and is quite efficient:

from collections import defaultdict, deque

A=[5,20,13,1]

_sorted_indices = defaultdict(deque)

for i,x in enumerate(sorted(A)):
    _sorted_indices[x].append(i)

indices = [_sorted_indices[x].popleft() for x in A]

Output:

>>> print(indices)
[1, 3, 2, 0]

CodePudding user response:

If duplicates are allowed use this:

A = [5, 20, 13, 20, 1]
d = {i: v for i, v in enumerate(sorted(A))}
output = []
print(d)
for x in A:
    for k in d:
        if d[k] == x and k not in output:
            output.append(k)
            break
print(output)

Output:

[1, 3, 2, 4, 0]

If not you can use the simple:

output = [sorted(A).index(i) for i in A]
print(output)

Output:

[1, 3, 2, 0]

CodePudding user response:

You can sort the array first and create the array of indices using index method.

A=[5,20,13,1]
B = sorted(A)
result = [B.index(k) for k in A]
print(result)
# [1, 3, 2, 0]

Caveat: The result will have duplicate index numbers if the original list has duplicate numbers.

Edit: Another interesting way that handles duplicates.

A = [5, 20, 20, 13, 1, 13]
sorted(range(len(A)), key=A.__getitem__)
# [4, 0, 3, 5, 1, 2]

CodePudding user response:

You can keep track of your elements like this. Create a mapping from element value to the list of indices it had on the original list to ensure duplicate values are handled in the correct order.

Get the result by popping indices one by one for each value from the original list that you encounter.

from collections import defaultdict
A = [5, 20, 13, 1]
d = defaultdict(list)
for (i, v) in enumerate(sorted(A)):
    d[v].append(i)

result = [d[v].pop(0) for v in A]

# [1, 3, 2, 0]

  •  Tags:  
  • Related