简体   繁体   中英

Python Order Alphabetically without preceding zeros for numbers less than 10

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM