Quantcast
Channel: How do I sort a list with positives coming before negatives with values sorted respectively? - Stack Overflow
Viewing all articles
Browse latest Browse all 12

How do I sort a list with positives coming before negatives with values sorted respectively?

$
0
0

I have a list that contains a mixture of positive and negative numbers, as the following

lst = [1, -2, 10, -12, -4, -5, 9, 2]

What I am trying to accomplish is to sort the list with the positive numbers coming before the negative numbers, respectively sorted as well.

Desired output:

[1, 2, 9, 10, -12, -5, -4, -2]

I was able to figure out the first part sorting with the positive numbers coming before the and negative numbers, unfortunately this does not respectively sort the positive and negative numbers.

lst = [1, -2, 10, -12, -4, -5, 9, 2]lst = sorted(lst, key=lambda o: not abs(o) == o)print(lst)>>> [1, 10, 2, 9, -2, -12, -4, -5]

How may I achieve my desired sorting with a pythonic solution?


Viewing all articles
Browse latest Browse all 12

Latest Images

Trending Articles



Latest Images