how to return the order index of each element of a list?

Viewed 323

I have a list of Numbers, say L=[50, 10, 30], and in Python I want to return a list giving the order index of each element in L, which would be this output: [2, 0, 1].

Though it seems to be a simple task, many questions on this site (here here and here for instance) focus on the other way round, meaning the index from the sorted list point of view: [1, 2, 0], which is not what I want.

Thanks,

EDIT: about repetitions, i'd like them to be counted as well (draws taken in order of appearance). [50,30,10,30] would give [3,1,0,2]

4 Answers

One liner:

l = [50, 30, 10, 30]
numpy.argsort(numpy.argsort(l))
# array([3, 1, 0, 2])

it is the index list of the sorted order:

def sort_order(lst):
    orders = sorted(list(range(len(lst))), key=lambda x: lst[x])
    ret = [0] * len(lst)
    for i in range(len(ret)):
        ret[orders[i]] = i
    return ret

print(sort_order([50, 10, 30]) # [2,0,1]

Enumerating and sorting twice like:

L = [50, 10, 30]
x = tuple(k[1] for k in sorted((x[1], j) for j, x in enumerate(
    sorted((x, i) for i, x in enumerate(L)))))
print(x)

Results:

(2, 0, 1)

Using dicts..

L = [50, 10, 30, 10, 30]
d = {counter:value for counter,value in enumerate(L)} #L is your list
sorteddict = sorted(d.items(), key=lambda x: x[1])
d2 = {counter:value for counter,value in enumerate(sorteddict)}
order_index = {d2[i][0]:i for i in d2}
print(order_index.values())

enter image description here

Related