Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list in python

Tags:

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?

like image 203
Diego Martínez Giardini Avatar asked Oct 05 '13 16:10

Diego Martínez Giardini


People also ask

How do you sort a list in Python?

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.

What is sort () in Python?

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.

What does list sort () do?

The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items.

Can you sort a list of lists in Python?

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.


1 Answers

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]
like image 63
Ashwini Chaudhary Avatar answered Oct 24 '22 02:10

Ashwini Chaudhary