2

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

Stef
  • 13,242
  • 2
  • 17
  • 28
Dawny33
  • 10,543
  • 21
  • 82
  • 134
  • Do any of these answer your question? https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sort https://stackoverflow.com/questions/2545532/python-analog-of-phps-natsort-function-sort-a-list-using-a-natural-order-alg https://stackoverflow.com/questions/4813061/non-alphanumeric-list-order-from-os-listdir/48030307#48030307 https://stackoverflow.com/questions/34518/natural-sorting-algorithm – Stef Sep 17 '20 at 12:21
  • 1
    Your own solution `.sort(key=lambda x: int(x.split('-')[0]))` is almost correct; you can fix it like this: `.sort(key=lambda x: [int(n) for n in x.split('-')])` – Stef Sep 17 '20 at 12:28
  • Thanks for the pointer @Stef. Split and sort makes sense :) – Dawny33 Sep 17 '20 at 12:37

1 Answers1

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']
>>> 
Paul M.
  • 10,481
  • 2
  • 9
  • 15
  • Ironically enough, `sorted(items)` gives the wanted result for your particular example of `items = ["31-1", "31-0", "0-0", "0-2", "0-1"]`. – Stef Sep 17 '20 at 12:31