Search code examples
pythonlistsortingprefix

sorting list in python


if I have a list of strings e.g. ["a143.txt", "a9.txt", ] how can I sort it in ascending order by the numbers in the list, rather than by the string. I.e. I want "a9.txt" to appear before "a143.txt" since 9 < 143.

thanks.


Solution

  • It's called "natural sort order", From http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

    Try this:

    import re 
    
    def sort_nicely( l ): 
      """ 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('([0-9]+)', key) ] 
      l.sort( key=alphanum_key )