Using Python 3.x, I have a list of strings for which I would like to perform a natural alphabetical sort.
Natural sort: The order by which files in Windows are sorted.
For instance, the following list is naturally sorted (what I want):
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
And here's the "sorted" version of the above list (what I have):
['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
I'm looking for a sort function which behaves like the first one.
Let's analyse the data. The digit capacity of all elements is 2. And there are 3 letters in common literal part
'elm'
.So, the maximal length of element is 5. We can increase this value to make sure (for example, to 8).
Bearing that in mind, we've got a one-line solution:
without regular expressions and external libraries!
Explanation:
I suggest you simply use the
key
keyword argument ofsorted
to achieve your desired listFor example:
Acknowledgments:
Bubble Sort Homework
How to read a string one letter at a time in python
The above answers are good for the specific example that was shown, but miss several useful cases for the more general question of natural sort. I just got bit by one of those cases, so created a more thorough solution:
Test code and several links (on and off of StackOverflow) are here: http://productarchitect.com/code/better-natural-sort.py
Feedback welcome. That's not meant to be a definitive solution; just a step forward.
Try this:
Output:
See it working online: ideone.
Code adapted from here: Sorting for Humans : Natural Sort Order.
One option is to turn the string into a tuple and replace digits using expanded form http://wiki.answers.com/Q/What_does_expanded_form_mean
that way a90 would become ("a",90,0) and a1 would become ("a",1)
below is some sample code (which isn't very efficient due to the way It removes leading 0's from numbers)
output: