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

I have wrong result with sorting sting numbers

I have a folder with names of files and I want to do list with that names and sort it, but the result is weird. Do you know what I do wrong?

list = [ '10.50-178.pom', '15.00-178.pom','100.0-178.pom', '11.00-178.pom', '110.0-178.pom',
'120.0-178.pom', '130.0-178.pom', '10.00-178.pom', '140.0-178.pom' ]

print(sorted(list))

result: ['10.00-178.pom', '10.50-178.pom', '100.0-178.pom', '11.00-178.pom', '110.0-178.pom', '120.0-178.pom', '130.0-178.pom', '140.0-178.pom', '15.00-178.pom']

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

>Solution :

You will need to indicate that the first five characters are actually a number, because now every character is considered separetly.

lista = ['10.50-178.pom', '15.00-178.pom', '100.0-178.pom', '11.00-178.pom', '110.0-178.pom',
        '120.0-178.pom', '130.0-178.pom', '10.00-178.pom', '140.0-178.pom']

def take_elem(elem):
    return float(elem[:4])

sorted_list = sorted(lista, key=take_elem)
print(sorted_list)   
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