How to sort with condition in python

How to create sort with conditions in python? Say if I have a list

a: [-1, 3, 4, 2, -1, -1, 1, 0]

How to sort only those elements that are not equal to -1? (In reply:

[-1, 0, 1, 2, -1, -1, 3, 4] )

How to sort all other items? (In response to a :) [-1, 3, -1, 2, 1, -1, 4, 0] The code syntax is incorrect, but does it look like something like that?

result=sorted(a, key=lambda x: x!=-1,reverse=True)
result=sorted(a, key=lambda x: [::2],reverse=True)
+4
source share
2 answers

If you are interested in the vector approach, this is possible through a third-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?

+2
source

next iter s, :

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]))

:

[-1, 0, 1, 2, -1, -1, 3, 4]
+2

Source: https://habr.com/ru/post/1696039/


All Articles