Reproducible code :
import numpy as np
lst = [-69,-68,-58,-39,-18,-11,-10,-9,-8,0,2,7,7,21,31,31,34,46,49,89,128]
Tried the code:
sorted_list = [sorted(lst).index(x) for x in lst]
sorted_list
Expected output:
[-1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
CodePudding user response:
You can use either map
or a list comprehension to replace every negative number with -1. This can be done with a conditional:
# list comprehension
l = [(-1 if x < 0 else x) for x in l]
# map
l = list(map(lambda x: -1 if x < 0 else 0, l))
Or if the numbers are integers, then -1
is the "highest" possible negative number, so you can use max
:
# list comprehension
l = [max(-1, x) for x in l]
# map
l = list(map(lambda x: max(-1, x), l))
Then you can sort the resulting list with list.sort
or sorted
.
Final code:
def sorted_and_minus1(l):
return sorted(max(-1, x) for x in l)
lst = [-69,-68,-58,-39,-18,-11,-10,-9,-8,0,2,7,7,21,31,31,34,46,49,89,128]
sorted_lst = sorted_and_minus1(lst)
print(sorted_lst)
# [-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 2, 7, 7, 21, 31, 31, 34, 46, 49, 89, 128]
CodePudding user response:
Create a Pandas Series, then replace negatives with -1, then sort them :
import pandas as pd
import numpy as np
lst = [-69,-68,-58,-39,-18,-11,-10,-9,-8,0,2,7,7,21,31,31,34,46,49,89,128]
s = pd.Series(lst)
s[s<0] = -1
print(s.sort_values())