0

how would you sort a list of numbers like 5.1, 5.2, 5.3,... 5.10,5.11 in a way that doesn't put 5.10 and 5.11 after 5.1 in Python. I basically want python to realize that I don't actually mean 5.10 but section 5, subsection 10.

Natsu TRO
  • 21
  • 1

2 Answers2

5

You could treat it in the same way as a version number, for example:

>>> from distutils.version import LooseVersion

>>> a = ["5.1", "5.10", "5.11", "5.2"]

>>> sorted(a, key=LooseVersion)
['5.1', '5.2', '5.10', '5.11']

The assumption here is that you have the data in the form of strings. (It is not meaningful to distinguish e.g. 5.1 and 5.10 as floats.)

alani
  • 12,573
  • 2
  • 13
  • 23
2

There's a library called natsort which does exactly that:

from natsort import natsorted
a = ["5.1", "5.10", "5.11", "5.2"]
print(natsorted(a))
# ['5.1', '5.2', '5.10', '5.11']
Jan
  • 42,290
  • 8
  • 54
  • 79