Sep-23-2022, 07:53 AM
(This post was last modified: Sep-23-2022, 07:53 AM by deanhystad.)
I think DeaD_EyE is not interpreting the question correctly. I do not think "unique" means that the lst should be pared down to only contain unique values. I think the problem is the way the index sort was done returned non-unique values. The problem is caused by using "index" which returns the first match, not the index of the element.
To solve the problem, create a list of index values, and sort these using a key that references the original list. This is what perfingo did with the index, value tuples. Another way to do the same thing is create a separate list of index values and sort the index list using a key that references the original list.
You could also do this with numpy's argsort()
To solve the problem, create a list of index values, and sort these using a key that references the original list. This is what perfingo did with the index, value tuples. Another way to do the same thing is create a separate list of index values and sort the index list using a key that references the original list.
lst = [48,52,35,35,44,35] index = range(len(lst)) sorted_index = sorted(index, key=lambda i: lst[i]) print(sorted_index)I like perfingo's method because it produces the sorted list and the sorted index list at the same time. I would use that if I needed both results. If I only needed the sorted index list I might use the separate array.
You could also do this with numpy's argsort()
import numpy as np lst = np.array([48,52,35,35,44,35]) print(lst.argsort())