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)
M-M
  • 881
  • 2
  • 10
  • 19

2 Answers2

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]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • 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. – M-M Apr 10 '18 at 23:49
  • @JingLi I updated the solution to include a function that can receive two parameters: the list to be sorted, and the value to avoid. – Ajax1234 Apr 10 '18 at 23:52
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?

jpp
  • 159,742
  • 34
  • 281
  • 339