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 jpmc26 for How do I sort a list with positives coming before negatives with values sorted respectively?

$
0
0

You could just sort by the negative of the element's inverse:

from __future__ import divisionsorted(lst, key=lambda i: 0 if i == 0 else -1 / i)

Taking the inverse switches the order of the magnitudes (larger numbers in the middle, smaller on the outside). Taking the negative reverses the order (positives first, negatives last).

Be aware of the size of your numbers of course and if they'll cause any over- or underflow issues.


Viewing all articles
Browse latest Browse all 12

Trending Articles



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