[英]How to do a numeric reverse sort in python on a list which contains numbers and letters
我的清单是这样的:
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
这是因为它没有被解释为数字,但是我无法将整个字符串转换为浮点数。 我想要的是第一部分的数字排序:
13.87|second sentence
10.987|first sentence
9.098|third sentence
我尝试使用itemgetter,但似乎找不到我想要的东西。 在bash中可以轻松解决
sort -k
在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
参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.