Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by absolute value without changing to absolute value

I want to sort a tuple using abs() without actually changing the elements of the tuple to positive values.

def sorting(numbers_array):
    return sorted(numbers_array, key = abs(numbers_array))


sorting((-20, -5, 10, 15))

According to the python wiki (https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions), the sorted(list, key=) function is suppose to sort with the parameter key without actually altering the elements of the list. However, abs() only takes int() and I haven't worked out a way to make that tuple into an int, if that's what I need to do.

like image 863
Nick Kremer Avatar asked Jan 12 '15 15:01

Nick Kremer


People also ask

How do I sort absolute value in pandas?

We will use the abs() method to convert the actual value into absolute value and then we will use the sort_values() method to sort the values by absolute values. This method works on a particular column and it can sort the values either in ascending order or in descending order.

How do you sort a panda series?

Sort the Series in Ascending Order By default, the pandas series sort_values() function sorts the series in ascending order. You can also use ascending=True param to explicitly specify to sort in ascending order. Also, if you have any NaN values in the Series, it sort by placing all NaN values at the end.

How do you use the sort function in Python?

Python sorted() FunctionThe sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.


1 Answers

You need to give key a callable, a function or similar to call; it'll be called for each element in the sequence being sorted. abs can be that callable:

sorted(numbers_array, key=abs)

You instead passed in the result of the abs() call, which indeed doesn't work with a whole list.

Demo:

>>> def sorting(numbers_array):
...     return sorted(numbers_array, key=abs)
... 
>>> sorting((-20, -5, 10, 15))
[-5, 10, 15, -20]
like image 192
Martijn Pieters Avatar answered Sep 22 '22 11:09

Martijn Pieters