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]
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With