Wondercricket - 1 year ago 53
Python Question

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

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?

You could just use a regular sort, and then bisect the list at 0:

``````>>> lst
[1, -2, 10, -12, -4, -5, 9, 2]
>>> from bisect import bisect
>>> lst.sort()
>>> i = bisect(lst, 0)
>>> lst[i:] + lst[:i]
[1, 2, 9, 10, -12, -5, -4, -2]
``````

Note that slicing like `lst[:] == lst[:n] + lst[n:]` is an invariant in Python.

Another option would be to use a tuple as a sort key, and take advantage of lexicographical ordering of tuples:

``````>>> sorted(lst, key=lambda x: (x<0, x))
[1, 2, 9, 10, -12, -5, -4, -2]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download