Reputation: 901
How do I construct a sort with conditions in python? Let's say if I have a list
a: [-1, 3, 4, 2, -1, -1, 1, 0]
How do I sort only the elements that is not -1? (In return:
[-1, 0, 1, 2, -1, -1, 3, 4] )
How do I sort every other element?
(In return a: [-1, 3, -1, 2, 1, -1, 4, 0]
)
The syntax of the code is wrong, but would it be something similar to this?
result=sorted(a, key=lambda x: x!=-1,reverse=True)
result=sorted(a, key=lambda x: [::2],reverse=True)
Upvotes: 4
Views: 2267
Reputation: 164623
If a vectorised approach interests you, this is possible via 3rd party library numpy
:
import numpy as np
a = np.array([-1, 3, 4, 2, -1, -1, 1, 0])
a[a!=-1] = np.sort(a[a!=-1])
# array([-1, 0, 1, 2, -1, -1, 3, 4])
Sorting every other element is equally trivial:
a[::2] = np.sort(a[::2])
# array([-1, 3, -1, 2, 1, -1, 4, 0])
Related: Why NumPy instead of Python lists?
Upvotes: 2
Reputation: 71451
You can use next
and iter
after sorting all contents from s
that are positive:
def sort_by(s, avoid = -1):
sorted_vals = iter(sorted(filter(lambda x:x >= 0, s)))
return [i if i == avoid else next(sorted_vals) for i in s]
print(sort_by([-1, 3, 4, 2, -1, -1, 1, 0]))
Output:
[-1, 0, 1, 2, -1, -1, 3, 4]
Upvotes: 2