2

I'm currently working on trying to sort a list of string file paths in the same manor as Windows Explorer does. I've been looking at several natural/human sorting algorithms that have been posted (especially ones in the natsort package) but all of them have the same problem.

Given a directory containing files "0.jpg", "00.jpg" and "000.jpg", Windows will sort them in order of decreasing precision, that is: 000.jpg, 00.jpg. 0.jpg.

All of the algorithms I've tried will sort them in the opposite order. I'm not sure how to get the desired behavior. Any advice would be appreciated.

2
  • Sort => Invert? Windows will sort whichever way you choose, depending on whether that column is sorted in ascending or descending order... Commented Aug 14, 2015 at 7:09
  • Hey i don't know it might be very late, but i have added an answer with natsort which can do this job Commented Jan 2, 2022 at 18:14

2 Answers 2

5

natsort python package can actually help in your case

from natsort import os_sorted
a = ["0.jpg","00.jpg","000.jpg"]
print(os_sorted(a))

Output:

['000.jpg', '00.jpg', '0.jpg']
Sign up to request clarification or add additional context in comments.

Comments

2

This should work but it's a bit clunky:

  • Determine the longest file name in the list
  • Right-pad all file names to the length of the longest name with a high-value character that doesn't appear in any of the file names (such as '~') inserting it before the file extension
  • Sort as normal
  • Remove the inserted character before displaying the results

So

0.jpg, 00.jpg, 000.jpg, 1.jpg

becomes:

0~~.jpg, 00~.jpg, 000.jpg, 1~~.jpg

when sorted:

000.jpg, 00~.jpg, 0~~.jpg, 1~~.jpg

and finally:

000.jpg, 00.jpg, 0.jpg, 1.jpg

2 Comments

I ended up doing this, but instead of "~", I used chr(65535).
Actually, scratch that. I found another edge case that get introduced with this method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.