3

I have a list of integers. Each number can appear several times, the list is unordered.

I want to get the list of relative sizes. Meaning, if for example the original list is [2, 5, 7, 7, 3, 10] then the desired output is [0, 2, 3, 3, 1, 4]

Because 2 is the zero'th smallest number in the original list, 3 is one'th, etc.

Any clear easy way to do this?

Oria Gruber
  • 1,513
  • 2
  • 22
  • 44
  • 1
    Almost duplicate of [Efficient method to calculate the rank vector of a list in Python - Stack Overflow](https://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python) -- although it's slightly different when there are ties. The methods are mostly the same except `set()`. – user202729 Jan 11 '21 at 10:32
  • In particular the method here is `dense` instead of `average`. – user202729 Jan 11 '21 at 10:41

1 Answers1

3

Try a list comprehension with dictionary and also use set for getting unique values, like below:

>>> lst = [2, 5, 7, 7, 3, 10]
>>> newl = dict(zip(range(len(set(lst))), sorted(set(lst))))
>>> [newl[i] for i in lst]
[0, 2, 3, 3, 1, 4]
>>> 

Or use index:

>>> lst = [2, 5, 7, 7, 3, 10]
>>> newl = sorted(set(lst))
>>> [newl.index(i) for i in lst]
[0, 2, 3, 3, 1, 4]
>>>
U13-Forward
  • 69,221
  • 14
  • 89
  • 114