Home > database >  Sort a list by negative numbers, zeros, then positive Python
Sort a list by negative numbers, zeros, then positive Python

Time:09-21

How do I make a new list where the numbers are sorted first in negative, then 0's and then positive numbers in Python?

For example if I have the list a = [3, -5, 1, 0, -1, 0, -2] I want the new list to be [-5, -1, -2, 0, 0, 3, 1]

CodePudding user response:

You can set a sort key:

a.sort(key=lambda i:1 if i>0 else 0 if i==0 else -1)

You can change this to split by any predicate.

CodePudding user response:

You could do something like that

b = [x for x in a if x < 0]   [x for x in a if x == 0]   [x for x in a if x > 0]

CodePudding user response:

sorting array based on there number and occuerence

def func(array):
    dic = {-1:[], 0:[], 1:[]}
    for i in array:
        if i<0:
            dic[-1].append(i)
        elif i==0:
            dic[0].append(i)
        elif i>0:
            dic[1].append(i)
    res = []
    for i in [-1, 0, 1]:
        res.extend(dic[i])
    return res
arr = [3, -5, 1, 0, -1, 0, -2]
sol = func(arr)
print(sol) # [-5, -1, -2, 0, 0, 3, 1]
  • Related