python反向数字_如何在包含数字和字母的列表上的python中进行数字反向排序

My list is like this:

10.987|first sentence

13.87|second sentence

9.098|third sentence

if I do something like:

for x in my_list:

sorted(my_list, reverse=True)

I logically get:

9.098|third sentence

13.87|second sentence

10.987|first sentence

This is because it is not interpreted as a number but I can't convert the whole string to a float. What I want is a numeric sort of the first part:

13.87|second sentence

10.987|first sentence

9.098|third sentence

I tried using itemgetter but I can't seem to find exactly what I am looking for. In bash this can easily be solved with

sort -k

Is there an equivalente to do this in python?

解决方案

Here is one way.

lst = ['10.987|first sentence',

'13.87|second sentence',

'9.098|third sentence']

res = sorted(lst, key=lambda x: -float(x.split('|')[0]))

Result

['13.87|second sentence',

'10.987|first sentence',

'9.098|third sentence']

Explanation

sorted takes an argument key which allows you to specify a custom (lambda) function on which to sort.

The lambda function splits by "|" and extracts the first part to get the numeric component.

To sort numerically, we convert to float and finally negate to ensure descending order.

Instead of negation, reverse=True argument may be used.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值