5

I have a simple list of values of which I need the index sorted by the original value order (max to min).

Let's assume the list is

maxList = [7, 3, 6, 9, 1, 3]

The result should be:

indexedMaxList = [3, 0, 2, 1, 5, 4]

What I tried so far:

def ClusteringOrder(maxList):
    sortedMaxList = maxList.copy()
    sortedMaxList.sort(reverse=True)
    indexedMaxList = []
    for i in range(len(maxList)):
        indexedMaxList.append(maxList.index(sortedMaxList[i]))
    return(indexedmaxList)

Problem is obviously, doing it this way returns the index of the first occurrence of duplicate values. In this case, the double 3 will return a 1 two times, hence the result will be:

indexedMaxList = [3, 0, 2, 1, 1, 4]

Is there any simple way of doing this to get the actual positions back?

pault
  • 41,343
  • 15
  • 107
  • 149
nordlicht.22
  • 61
  • 1
  • 4
  • You can use `numpy.argsort` if you're open to using `numpy`: https://stackoverflow.com/questions/16486252/is-it-possible-to-use-argsort-in-descending-order. In your case: `indexedMaxList = np.argsort([7, 3, 6, 9, 1, 3])[::-1][:n].tolist()` – pault Aug 06 '19 at 18:27
  • Almost duplicate of [How to get indices of a sorted array in Python](https://stackoverflow.com/questions/6422700/how-to-get-indices-of-a-sorted-array-in-python) – pault Aug 06 '19 at 18:32

2 Answers2

6

You can combine enumerate() with custom key= parameter in sorted():

maxList = [7, 3, 6, 9, 1, 3]

print([i[0] for i in sorted(enumerate(maxList), key=lambda k: k[1], reverse=True)])

Prints:

[3, 0, 2, 1, 5, 4]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
4
import numpy
maxList = [7, 3, 6, 9, 1, 3]
print(np.flip(np.argsort(maxList)))

Output

[3 0 2 5 1 4]