Sort a list of percent

I have the following list:

l = ['50%','12.5%','6.25%','25%']

Which I would like to sort in the following order:

['6.25%','12.5%','25%','50%']

Using l.sort () gives:

['12.5%','25%','50%','6.25%']

Any cool tricks to easily sort these lists in Python?

+3
source share
1 answer

You can sort using a custom key

b =['52.5%', '62.4%', '91.8%', '21.5%']
b.sort(key = lambda a: float(a[:-1]))

This applies to the set, but uses a numeric value as a key (that is, it strips "%" in a string and converts to float.

+15
source

Source: https://habr.com/ru/post/1744904/


All Articles