繁体   English   中英

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

[英]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.

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