Dawny33
Dawny33

Reputation: 11081

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"]

Upvotes: 2

Views: 886

Answers (1)

Paul M.
Paul M.

Reputation: 10799

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']
>>> 

Upvotes: 3

Related Questions