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

Answer by RootTwo for How do I sort a list with positives coming before negatives with values sorted respectively?

$
0
0

Sort the list in place twice like so:

lst = [1, -2, 10, -12, -4, -5, 9, 2]lst.sort()lst.sort(key=int(0).__gt__)      # key is True for items <= 0

This takes advantage of the fact the python sort function/method is stable. That means that items with the same value or key stay in the same order. The first sort puts all the items in order from smallest to largest. For the second sort, all the items < 0 get a key of True, all the items >= 0 get a key of False. Because True (1) > False (0), the second sort moves all the negative items to the end, without changing the order of the negative items.


Viewing all articles
Browse latest Browse all 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>