如何在包含数字和字母的列表上的python中进行数字反向排序 [英] How to do a numeric reverse sort in python on a list which contains numbers and letters
本文介绍了如何在包含数字和字母的列表上的python中进行数字反向排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的列表是这样的:
10.987|first sentence
13.87|second sentence
9.098|third sentence
如果我做类似的事情:
for x in my_list:
sorted(my_list, reverse=True)
我在逻辑上得到:
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
我尝试使用itemgetter,但似乎找不到我想要的东西.在bash中,可以很容易地用
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
在python中有等同的功能吗?
Is there an equivalente to do this in python?
推荐答案
这是一种方法.
lst = ['10.987|first sentence',
'13.87|second sentence',
'9.098|third sentence']
res = sorted(lst, key=lambda x: -float(x.split('|')[0]))
结果
['13.87|second sentence',
'10.987|first sentence',
'9.098|third sentence']
说明
-
sorted
带有参数key
,该参数允许您指定要在其上进行排序的自定义(lambda
)函数. -
lambda
函数用"|"分隔并提取第一部分以获取数字分量. - 要进行数字排序,我们转换为
float
,最后求和以确保降序. - 可以使用
reverse=True
参数代替否定符.
sorted
takes an argumentkey
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.
这篇关于如何在包含数字和字母的列表上的python中进行数字反向排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文