1

I tried the following code:

import numpy
s = [6,6,6,6,6]
print(numpy.argsort(s))

Output:

[0 1 2 3 4]

Expected Output: [4 3 2 1 0]

Another example sample code:

s = [5, 5, 2, 2, 3]
li = []

for i in range(len(s)):
    li.append([s[i], i])
li.sort()
sort_index = []

for x in li:
    sort_index.append(x[1])

print(sort_index)

Output:

[2, 3, 4, 0, 1]

Expected Output:

[3 2 4 1 0]

Could this unstable sort index return is possible in python?

DRV
  • 676
  • 1
  • 8
  • 22
  • 1
    What is the reasoning behind your expected output? – lllrnr101 Feb 23 '21 at 09:08
  • Consider a scenario all elements are distinct in that case it should return the index of the sorted element from the original list. – DRV Feb 23 '21 at 09:24
  • When duplicate elements are present like [6,6,6,6,6,6] it should return the sorted list index from last. – DRV Feb 23 '21 at 09:25

2 Answers2

2

You could do something like:

>>> s = [5, 5, 2, 2, 3]
>>> sorted(enumerate(s), key=lambda x:(x[1], -x[0]))
[(3, 2), (2, 2), (4, 3), (1, 5), (0, 5)]

And if you just wanted the indices,

>>> [x[0] for x in sorted(enumerate(s), key=lambda x:(x[1], -x[0]))]
[3, 2, 4, 1, 0]

Or for your other example:

>>> s = [6,6,6,6,6]
>>> [x[0] for x in sorted(enumerate(s), key=lambda x:(x[1], -x[0]))]
[4, 3, 2, 1, 0]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

I think what you are looking for is sorting in reverse order. am I right? There is already a thread for that: Python list sort in descending order the function is list.sort(reverse=True)

mrKawaii0
  • 11
  • 3
  • Actually, I want the original index of the sorted list but in case a duplicate element is present it should return the index from last. – DRV Feb 23 '21 at 09:20