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

后端 未结 1 1486
悲哀的现实
悲哀的现实 2020-12-22 08:10

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_         


        
相关标签:
1条回答
  • 2020-12-22 08:28

    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)
提交回复
热议问题