views:

96

answers:

1

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() yields:

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

Any cool tricks to sort these lists easily in Python?

+13  A: 

You can sort with a custom key

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

This resorts the set, but uses the numerical value as the key (i.e. chops of the '%' in the string and converts to float.

Il-Bhima
That won't work with '6.25%'. Did you mean `int(a[:-1])`?
Marcelo Cantos
Sorry misprint. These things happen :)
Il-Bhima
Ahh, cool - it almost worked I had to do a:b.sort(key = lambda a: float(str(a[:-1])))To make it fully functional.
mortenvp
No no, check it again. Sorry, in my half-asleep state I wrote 'str' instead of 'float. Sorry about that :)
Il-Bhima