Python's Equivalent to PHP's natsort for Natural Order Sorting
A frequently asked question in Python is how to sort a list in natural order, similar to PHP's natsort function. Unlike a standard sort, natural order considers numeric characters as numbers rather than strings.
For instance, consider sorting a list of filenames:
<code class="python">l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg'] l.sort()</code>
This standard sorting will result in:
['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
However, to achieve a natural order sorting, Python provides a key function that converts strings into numeric tuples if possible. This allows for proper numeric comparisons.
Here's a sample implementation:
<code class="python">import re def natsort_key(s): return map(int, re.findall(r'(\d+)', s))</code>
Applying this key during sorting yields the desired natural order:
<code class="python">l.sort(key=natsort_key)</code>
The output will be:
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']
Alternatively, if you require case-insensitive sorting, a more complete implementation can be used:
<code class="python">def natcasecmp(a, b): return natcmp(a.lower(), b.lower())</code>
This provides a case-insensitive natural order sorting.
The above is the detailed content of How to Achieve Natural Order Sorting in Python Like PHP's natsort?. For more information, please follow other related articles on the PHP Chinese website!