I have sorted a list in descending order, I am trying to find a way in which similar numbers re-appearing in the list will return equal position and the next unique number to return the next position. Example in this samplelist = [50, 40, 40, 30, 30, 20, 10]
50 should return 1, 40 returns 2, next 40 returns 2, 30 returns 4, next 30 returns 4 then 20 returns 6, 10 returns 7. Note that this will be a dynamic list. This is how far I have gone but it isn’t quite right.
samplelist = [10, 20, 30, 30, 40, 40, 50] samplelist.sort(reverse=True) print(samplelist) appearances = {} for index, value in enumerate(samplelist): appearances[value] = samplelist.count(value) for index, value in enumerate(appearances.items()): print(f'Position for {value[0]} = {index + value[1]}')
Advertisement
Answer
This can also be done using just the list.index
utility in python, which gives the index of the first occurrence of an element.
So, your program must do this :
appearances[value] = samplelist.index(value)
instead of this :
appearances[value] = samplelist.count(value) # It just returns the count of the value in samplelist