开发者

sort a list of percentages

开发者 https://www.devze.com 2022-12-30 08:37 出处:网络
I have the following list: l = [\'50%\',\'12.5%\',\'6.25%\',\'25%\'] Which I would like to sort in the following order:

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开发者_StackOverflow社区%','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 (i.e. chops of the '%' in the string and converts to float.

0

精彩评论

暂无评论...
验证码 换一张
取 消