Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative size in list python

Tags:

python

list

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?

like image 490
Oria Gruber Avatar asked Nov 19 '25 23:11

Oria Gruber


1 Answers

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]
>>>
like image 96
U12-Forward Avatar answered Nov 22 '25 15:11

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!