I’m working on a project where I need to sort a list of strings representing file names automatically. I have no problem reading the file names into a list, but I need to sort them in a special way that’s more complicated.
Base Python’s sort function will automatically sort a list to look like this:
#Not the actual file names I'm working with, but they follow this format
exampleList = ['x1-1_a.txt', 'x10-1_b.txt', 'x12-1_c.txt', 'x2-1_d.txt', 'x20-1_e.txt', 'xxt.txt']
exampleList.sort()
print(exampleList)
['x1-1_a.txt', 'x10-1_b.txt', 'x12-1_c.txt', 'x2-1_d.txt', 'x20-1_e.txt', 'xxt.txt']
I need the list to be sorted to look like this:
['x10-1_b.txt', 'x1-1_a.txt', 'x12-1_c.txt', 'x20-1_e.txt', 'x2-1_d.txt', 'xxt.txt']
I’ve tried looking into a bunch of other threads about list sorting but none have exactly answered how to do this specific case where “10” comes before “1-“, but “12” comes after “1-“. Natural sort and other niche types of sorting don’t seem to be useful to me here. Does anyone know how I can solve this?
Edit:
Here is an expanded list of how I want the strings to be sorted:
'x10-1', 'x1-1', 'x11-1', 'x12-1', 'x13-1', 'x14-1', 'x15-1', 'x16-1', 'x17-1', 'x18-1', 'x19-1', 'x20-1', 'x2-1', 'x21-1', ..., 'xx'
Essentially I want the files ordered first by if they are numeric, then I want the numeric characters to be ordered so that ’10’ comes before ‘1-‘, ‘1-‘ comes before ’11’ and then 11-19 are ordered normally, with the process repeating at ’20’, ‘2-‘, and 21-29
6