4

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)

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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]

2 Comments

Thank you for showing this! Although the answer for this list is correct, But if I want to sort only the numbers that's not -1....so if I have -2 in my list, this will not work.
@JingLi I updated the solution to include a function that can receive two parameters: the list to be sorted, and the value to avoid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.