简体   繁体   中英

Sorting strings by multiple substrings in Python

I have a list of filenames in the following format <number>-<number>

Example below:

0-0
1-0
1-1
1-2
1-3

...

31-0
31-1
31-2

I want to read them as a sorted list. When I do sort() on the listdir() output, 10-x is coming right after the 1-x series.

When I do .sort(key=lambda x: int(x.split('-')[0])) , I get the first number sorted, but the second one(the one after the hyphen are not sorted). Example: ["21-3", "21-0", "21-2", "21-1"]

So, how do I make sure that I can read my files with the filenames sorted according to the number before the hyphen in the filename and also sorted according to the second number in the filename(the one after the hyphen) ?

Desired output:

["0-0", "1-0", "1-1", "1-2", ... "31-0", "31-1", "31-2", "31-3"]

items = ["31-1", "31-0", "0-0", "0-2", "0-1"]

print(sorted(items, key=lambda s: tuple(map(int, s.split("-")))))

Output:

['0-0', '0-1', '0-2', '31-0', '31-1']
>>> 

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