I have this list
[1,-5,10,6,3,-4,-9]
But now I want the list to be sorted like this:
[10,-9,6,-5,-4,3,1]
As you can see I want to order from high to low no matter what sign each number has, but keeping the sign, is it clear?
sort() is one of Python's list methods for sorting and changing a list. It sorts list elements in either ascending or descending order. sort() accepts two optional parameters. reverse is the first optional parameter.
The sort() method is a built-in Python method that, by default, sorts the list in ascending order. However, you can modify the order from ascending to descending by specifying the sorting criteria.
The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items.
Python List sort() Method Syntax. The Python sort() method sorts the elements of a list in a given order, including ascending or descending orders. The method works in place, meaning that the changed list does not need to be reassigned in order to modify the list.
Use abs
as key to the sorted
function or list.sort
:
>>> lis = [1,-5,10,6,3,-4,-9]
>>> sorted(lis, key=abs, reverse=True)
[10, -9, 6, -5, -4, 3, 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With