Home > Software engineering >  I have wrong result with sorting sting numbers
I have wrong result with sorting sting numbers

Time:12-04

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']

CodePudding user response:

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)   
  • Related