Manipulating tuples in python
From raju
sort by absolute value
sorted(a, key=abs)
where a is a tuple. The sorted function does not alter the input array.
$ python Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 14:00:49) [MSC v.1915 64 bit (AMD64)] on win32 >>> a = (-20, 10, -5, 15) >>> sorted(a) [-20, -5, 10, 15] >>> a (-20, 10, -5, 15) >>> sorted(a, key=abs) [-5, 10, 15, -20] >>> a (-20, 10, -5, 15)
Another way:
sorted(a, key=lambda v: -v if v < 0 else v)
>>> a (-20, 10, -5, 15) >>> sorted(a, key=lambda v: -v if v < 0 else v) [-5, 10, 15, -20]