Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort numeric strings with 2 decimal points in python

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..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance

>Solution :

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('.')])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading