Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort python list of strings of numbers

Tags:

python

I am trying to sort list of strings containing numbers

a = ["1099.0","9049.0"] a.sort() a ['1099.0', '9049.0']  b = ["949.0","1099.0"] b.sort()      b ['1099.0', '949.0']  a ['1099.0', '9049.0'] 

But list b is sorting and not list a

like image 248
Vaibhav Jain Avatar asked Jul 04 '13 15:07

Vaibhav Jain


People also ask

How do you sort a list containing strings?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .

How do you sort a list of strings in Python without sorting?

You can use Nested for loop with if statement to get the sort a list in Python without sort function. This is not the only way to do it, you can use your own logic to get it done.


2 Answers

You want to sort based on the float values (not string values), so try:

>>> b = ["949.0","1099.0"] >>> b.sort(key=float) >>> b ['949.0', '1099.0'] 
like image 137
arshajii Avatar answered Sep 30 '22 13:09

arshajii


use a lambda inside sort to convert them to float and then sort properly:

a = sorted(a, key=lambda x: float(x)) 

so you will mantain them as strings but sorted by value and not lexicographically

like image 22
Samuele Mattiuzzo Avatar answered Sep 30 '22 13:09

Samuele Mattiuzzo