简体   繁体   English

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

[英]How to do a numeric reverse sort in python on a list which contains numbers and letters

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. 我尝试使用itemgetter,但似乎找不到我想要的东西。 In bash this can easily be solved with 在bash中可以轻松解决

sort -k

Is there an equivalente to do this in python? 在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. sorted使用参数key ,可让您指定要进行排序的自定义( lambda )函数。
  • The lambda function splits by "|" lambda函数以“ |”分隔 and extracts the first part to get the numeric component. 并提取第一部分以获取数字分量。
  • To sort numerically, we convert to float and finally negate to ensure descending order. 为了进行数字排序,我们转换为float并最终求反以确保降序。
  • Instead of negation, reverse=True argument may be used. 代替否定,可以使用reverse=True参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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