0

So I'm trying to make a little chunk of code that can sort a list of string numerically. However, I've run into an issue with other solutions that I've found online.

I then try using this solution that I found

file_list= ['cfilename-1-45352.other_text.txt', 'afilename-1-67546.other_text.txt', 
            'zfilename-1-46762.other_text.txt', 'bfilename-1-00352.other_text.txt', 
            'ffilename-1-13527.other_text.txt'
           ]

def sort_nicely():
    """ Sort the given list in the way that humans expect.
    
    convert = lambda text: int(text) if text.isdigit() else text
    alphanum_key = lambda key: [ convert(c) for c in re.split("\d{5}", key) ]
    return alphanum_key

file_list.sort(key=sort_nicely())

However, when I run this code it sorts based on filename, but I want it to sort based on the five digit number in the filename. I would really appreciate any help.

  • "sorts based on filename, but I want it to sort based on the five digit number in the filename." The last file name in the list does not have a five digit number – It_is_Chris Jun 30 '21 at 20:13
  • Sorry, I intended for it to have a five digit number. Thanks for catching that – Stefan Larson Jul 01 '21 at 12:07

0 Answers0