简体   繁体   中英

sort a list of percentages

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?

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 (ie chops of the '%' in the string and converts to float.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM