Python's Analog to PHP's natsort Function: Natural Order Sorting
Natural sorting algorithms sort lists of strings in a human-readable order, grouping numbers and other characters together. Unlike the default sort method, which treats "12" as less than "3", natural sorts would produce ["1", "10", "12", "3"].
In Python, one can implement a natural sorting function using a custom key function. The following code snippet provides an implementation similar to PHP's natsort:
<code class="python">import re def natural_key(string_): """See https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/""" return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]</code>
Example:
<code class="python">L = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg'] sorted(L) # Output: ['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg'] sorted(L, key=natural_key) # Output: ['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']</code>
For Unicode strings, use isdecimal() instead of isdigit(). For bytestrings on Python 2, bytestring.decode().isdigit() should be used.
The above is the detailed content of How to Implement Python's Equivalent of PHP's natsort Function?. For more information, please follow other related articles on the PHP Chinese website!