Search code examples
pythonsortingreindex

How to renumber reverse-sorted list of integers?


I have a list of numbers like this:

[687, 687, 683, 683, 677, 662....] 

It is sorted in descending order and has many numbers.

I want to represent it like, the greater the number in the list, I want to give it the smallest value and so on. Like 687 becomes 0, then 683 becomes 1, then 677 becomes 2 and so on.

Is there a way to do this?

EDIT:

Actually, I want to represent the new_list as [0,0,4,4,10,25..] such that highest element gets 0, then the next element is the difference of the two numbers in the original list + the previous number in the new_list, like we get 4 by doing (687-683) + 0 and so on. How to do that?


Solution

  • myList = [687, 687, 683, 683, 677, 662]
    unique_sorted_list = sorted(list(set(myList)), reverse = True)
    result = []
    for i in range(len(unique_sorted_list)):
        if i == 0:
            result.append((unique_sorted_list[i], i))
        else:
            result.append((unique_sorted_list[i], unique_sorted_list[i-1] - unique_sorted_list[i] + result[i-1][1]))
    
    result = [j[1] for i in myList for j in result if i==j[0]]  
    print result
    

    And we get Output as:

    [0, 0, 4, 4, 10, 25]