Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]

like image 836
agenis Avatar asked Jan 03 '19 04:01

agenis


People also ask

How do I get the index of duplicate items in a list?

Method #1 : Using loop + set() In this, we just insert all the elements in set and then compare each element's existence in actual list. If it's the second occurrence or more, then index is added in result list.

How do you find the index of a value in a list Python?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.


2 Answers

One liner:

l = [50, 30, 10, 30]
numpy.argsort(numpy.argsort(l))
# array([3, 1, 0, 2])
like image 66
Chris Avatar answered Sep 22 '22 06:09

Chris


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]
like image 45
Quang Hoang Avatar answered Sep 21 '22 06:09

Quang Hoang