How to sort numeric strings with 2 decimal points in python

Question:

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

Asked By: AKSHAY KADAM

||

Answers:

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('.')])
Answered By: Anuj Kumar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.