Sort a list by negative numbers, zeros, then positive Python
Question:
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]
Answers:
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.
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]
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]
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.
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]