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.