简体   繁体   中英

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. In bash this can easily be solved with

sort -k

Is there an equivalente to do this in 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.
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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