-1

I have some directories in linux having version as directory name :

1.1.0  1.10.0  1.5.0  1.7.0  1.8.0  1.8.1  1.9.1  1.9.2

I want to sort the above directories from lowest to highest version when i try to use .sort in python i end up getting below

['1.1.0', '1.10.0', '1.5.0', '1.7.0', '1.8.0', '1.8.1', '1.9.1']

which is actually incorrect , the 1.10.0 version is the gretest among all which should lie in the last index , is there a way to handle these things using python..

Thanks in advance

AKSHAY KADAM
  • 129
  • 8
  • This is happening because the versions are strings. I have a solution. Let me post it. :) – Anuj Kumar Nov 11 '22 at 08:23
  • [version-parser](https://pypi.org/project/version-parser/) can parse a number of formats. It also implements comparison so that they can be sorted. – Ouroborus Nov 11 '22 at 08:28

1 Answers1

0

Since your versions are of string datatype. We would have to split after each dot.

v_list = ['1.1.0','1.10.0','1.5.0','1.7.0','1.8.0','1.8.1','1.9.1','1.9.2']
v_list.sort(key=lambda x: list(map(int, x.split('.'))))

or you can also try this:

v_list = ['1.1.0','1.10.0','1.5.0','1.7.0','1.8.0','1.8.1','1.9.1','1.9.2']
v_list.sort(key=lambda x: [int(y) for y in x.split('.')])
Anuj Kumar
  • 1,092
  • 1
  • 12
  • 26
  • In both snippets, we used a "key" parameter to give our custom sorting technique. And, we are splitting each of our version strings on the basis of our '.' character. And then, we are converting each part of the version as an integer. Then, integer are sorted as it should be. – Anuj Kumar Nov 11 '22 at 08:32