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.
Asked
Active
Viewed 107 times
2 Answers
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
-
-
yes, I thought that the problem was different. And the other answer proposes something not in the original question answers too. Merge could be an option but the input is too different. – Jean-François Fabre Jul 03 '20 at 12:40