-2

I need a function that turns a list like [10,5,2,3,7] to a list like [4,2,0,1,3]

Basically a list [0,1,2,3,4...] but arranged in the order that the original list has, smallest to biggest.

I have no idea where to even start on a function like this. I have Python 3.5.2.

3 Answers3

0

This solution would work; however, there is probably a solution that is more space efficient. This solution does allow for repeat elements though.

l1 = [10, 5, 2, 3, 7] # Your list
l2 = sorted(l1) # Get the sorted version of our list.

# A dictionary containing each element and a list of the indices where they are found
element_indices = {}

for index, element in  enumerate(l2):
    if element not in element_indices:
        element_indices[element] = [index] # Store the index for each element when it is sorted
    else: # We have seen this element before
        element_indices[element].append(index)

l2 = [element_indices[value].pop() for value in l1] # Change each element to its sorted equivalent index

print(l2) # [4, 2, 0, 1, 3]
0

hiro protagonist's answer was close, but he indexed the wrong list.

>>> data = [10,5,2,3,7]
>>> sorted_list = sorted(data)
>>> [sorted_list.index(item) for item in data]
[4, 2, 0, 1, 3]

This wouldn't account for cases where you want to account for multiple occurrences and whatnot, but I'm not sure if that's required in your case.

OsmosisJonesLoL
  • 244
  • 1
  • 4
0

Try this:

>>> d = [10, 5, 2, 3, 7]
>>> [sorted(d).index(i) for i in d]
[4, 2, 0, 1, 3]
Cloudomation
  • 1,597
  • 1
  • 6
  • 15