44

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vaibhav Jain
  • 5,287
  • 10
  • 54
  • 114
  • 1
    `a` is already sorted. `1` is smaller that `9`. – Felix Kling Jul 04 '13 at 15:49
  • 1
    I want larger number to be at index `0` always and smaller number at index `0` – Vaibhav Jain Jul 04 '13 at 15:49
  • possible duplicate of [Sorting numbers in string format with Python](http://stackoverflow.com/questions/2597099/sorting-numbers-in-string-format-with-python) – Grijesh Chauhan Jul 04 '13 at 15:50
  • Possible duplicate of [Sorting a list of version strings](http://stackoverflow.com/questions/2574080/sorting-a-list-of-version-strings) – Teepeemm Nov 20 '15 at 18:00
  • 2
    Possible duplicate of [How to sort a list numerically?](https://stackoverflow.com/questions/3426108/how-to-sort-a-list-numerically) – Georgy Mar 07 '19 at 15:33

4 Answers4

93

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']
arshajii
  • 127,459
  • 24
  • 238
  • 287
21

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 maintain them as strings, but sorted by value and not lexicographically.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Samuele Mattiuzzo
  • 10,760
  • 5
  • 39
  • 63
13

In case anybody is dealing with numbers and extensions such as 0.png, 1.png, 10.png, 2.png... We need to retrieve and sort the characters before the extension since this extension does not let us to convert the names to floats:

myList = sorted(myList, key=lambda x: int(x[:-4]))

PD: After many years I have edited this answer changing float to int because I guess it is more efficient and more precise. It is a rare case to need floats for this purpose and it might bring errors.

Borja_042
  • 1,071
  • 1
  • 14
  • 26
  • 1
    remember to update the list too like `myList = sorted(myList, key=lambda x: float(x[:-4]))` – L.Goyal Mar 04 '21 at 20:48
  • If you want to update the list, you can also use `myList.sort(key=...)` instead of `sorted(myList, key=...)`, – Turun May 11 '23 at 18:48
3

Convert them to int or float or even decimal (since it has trailing numbers)

>>> b = [float(x) for x in b]
>>> b.sort()
>>> b
[949.0, 1099.0]