0

I would like to list a directory with Python. My directory only has files with name :

A1, A2, A3,..., A10, A11,..., B1,B2, ..., B10, B11 ...

Problem is that when I try with alphabetically order it with Python :

listQuery = os.listdir('C:\\query\\')
listQuery.sort()

I got the following order :

A1, A10, A11, ... ,A2 ... 

So my question is how can I first alphabetically order those and then order it with numbers

user2741700
  • 881
  • 3
  • 11
  • 21
  • 1
    This is often called "natural sorting": see [here](http://stackoverflow.com/a/4836734/1222578) for a simple Python implementation. – Marius Sep 27 '13 at 03:40

1 Answers1

1

Make a sorting key function, like:

def my_order(value):
    return (value[0], int(value[1:]))

Then use it to sort your list:

listQuery.sort(key=my_order)

This calls the my_order function on every value in the list, then sorts the list based on those newly computed values. This is also known as a "decorate-sort-undecorate" ("DSU") or "Schwartzian transform".

In this case, it creates a list of tuples like ('A', 2), ('A', 11), etc. Python sorts tuples based on their individual values. If two tuples have the same first value (like 'A'), it moves on to the next pair of values (2 and 11 here). Since both of those are integers, it would sort them numerically. It uses that ordering to sort the original list.

Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65